需求描述:
前端發送請求后,接收后端返回的文件流(一般是亂碼),實現導出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) }) },