1. 程式人生 > 其它 >【Excel】根據模板匯出Excel,後端返回檔案流前端下載

【Excel】根據模板匯出Excel,後端返回檔案流前端下載

需求描述:

前端傳送請求後,接收後端返回的檔案流(一般是亂碼),實現匯出Excel(根據模板生成Excel)

OrderManageController.cs

/// <summary>
/// 通過模板匯出Excel檔案
/// </summary>
/// <param name="orderInfoList"></param>
[HttpPost, Route("ExportConfirmOrderList")]
public FileResult ExportConfirmOrderList(List<OrderInfoView> orderInfoList)
{
    
string templatePath = ServerMapPath("/ui/FileTemplate/匯款資訊模板.xlsx"); string sheetName = "匯款資訊"; IWorkbook workBook; using (FileStream fs = System.IO.File.Open(templatePath, FileMode.Open, FileAccess.Read)) { workBook = new XSSFWorkbook(fs); } using (MemoryStream ms = new
MemoryStream()) { var sheet = workBook.GetSheet(sheetName); int startRowIndex = 2; //首行為提示文字,正式資料從第二行開始 foreach (var orderInfo in orderInfoList) { var row = sheet.CreateRow(startRowIndex++); row.CreateCell(0).SetCellValue(orderInfo.ProjectCode1Name); row.CreateCell(
1).SetCellValue(orderInfo.AppName); row.CreateCell(2).SetCellValue(orderInfo.PayAccountName); row.CreateCell(3).SetCellValue(orderInfo.OrderNo); row.CreateCell(4).SetCellValue(orderInfo.remitter); row.CreateCell(5).SetCellValue(orderInfo.RemittanceAmount.ToString()); row.CreateCell(6).SetCellValue(orderInfo.RemittanceMobile); row.CreateCell(7).SetCellValue(orderInfo.RemitRemark); } workBook.Write(ms); ms.Seek(0, SeekOrigin.Begin); //return File(bt, "application/vnd.ms-excel", "匯款資訊.xlsx"); 如果這樣寫一直報會無法找到關閉的流的錯誤,因為return的時候ms流已經被Dispose()了 byte[] bt = ms.ToArray(); //解決方案:將ms用中間量存下來,轉為byte陣列以便於關閉ms return File(bt, "application/vnd.ms-excel", "匯款資訊.xlsx"); } }

order.js

export function ExportConfirmOrderList(data) { 
    return request({
        url: '/order/ExportConfirmOrderList', 
        data, 
        method: 'post',
        responseType: 'blob'  //在請求介面的時候請求頭要新增responseType: 'blob'
    }) 
}

orderList.vue

exportConfrimOrderToExcel(){ 
  ExportConfirmOrderList(this.exportdata).then(res => {
    // console.log(res)
    var that = this
    //建立一個隱藏的a連線,
    const link = document.createElement('a')
    link.style.display = 'none'

    //Blob物件(是一個可以儲存二進位制檔案的容器);第一個引數為一個數據序列,可以是任意格式的值,第二個引數用於指定將要放入Blob中的資料的型別,比如:type: 'application/x-excel' 或 type: 'text/plain'
    const blob = new Blob([res], {type: 'application/vnd.ms-excel'})
    
    //URL.createObjectURL()方法通過傳入的引數(引數:用於建立url的file物件,Blob物件或者MediaSource物件),建立一個指向該引數物件的URL,繫結到建立a標籤的href屬性上
    link.href = URL.createObjectURL(blob)
    link.download = '匯款資訊.xlsx'   //自定義檔名

    //往body上面append這個a標籤,並執行a標籤的點選事件,進行檔案的匯出,最後匯出成功後,把a標籤從body上面移除
    document.body.appendChild(link) 
    link.click()  //模擬點選事件
    document.body.removeChild(link)
  })
},