.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)
        }
    })
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM