1. 程式人生 > 其它 >.Net Core WebApi+Vue實現檔案下載

.Net Core WebApi+Vue實現檔案下載

WebApi 控制器程式碼例項

[HttpPost]
public async Task<IActionResult> AcceptanceExportDate(AcceptanceEntryRequest input)
{
List<AcceptanceEntryResponse> exports = await _acceptanceEntryBusiness.AcceptanceExport(input);//獲取到你所要下載資料,我這裡呼叫查詢介面
using var package = new ExcelPackage();
ExcelWorksheet worksheet 
= package.Workbook.Worksheets.Add("資訊表"); List<string> titles = new List<string> { "客戶公司", "銷售公司", };//標題 for (int i = 0; i < titles.Count; i++) { worksheet.Cells[1, i + 1].Value = titles[i]; } int row = 2, col = 0; //內容 for (int i = 0; i < exports.Count; i++) { var Accptance = exports[i]; col
= titles.IndexOf("客戶公司") + 1; SetValue(worksheet, row, col, row, col, Accptance.CompanyName); col = titles.IndexOf("銷售公司") + 1; SetValue(worksheet, row, col, row, col, Accptance.SaleCompanyName); row++; } var excelData = package.GetAsByteArray(); var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
"; var fileName = "資訊表.xlsx"; return File(excelData, contentType, fileName); } public void SetValue(ExcelWorksheet worksheet, int row, int col, int endRow, int endCol, string text) { var range = worksheet.Cells[row, col, endRow, endCol]; range.Merge = true; range.Value = text; }

Vue程式碼例項

this.queryParam是你的查詢條件

 <a-button type="primary" @click="AcceptanceExport">匯出</a-button>

AcceptanceExport () {
  this.loading = true
  this.$http
    .post('/EShop/AcceptanceEntry/AcceptanceExportDate', this.queryParam, { responseType: 'blob' })
    .then((resJson) => {
      this.loading = false
        const blob = new Blob([resJson])
        const fileName = '資訊表.xls'
        if ('download' in document.createElement('a')) {
          // 非IE下載
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          elink.setAttribute('download', '資訊表.xlsx')
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 釋放URL 物件
          document.body.removeChild(elink)
        } else {
          // IE10+下載
          navigator.msSaveBlob(blob, fileName)
        }
    })
}