前端代码
//导出Excel
const exportMaintenanceOrderSettlementItemExcelClick = async () => {let url = `${VITE_APP_API_URL}/api/app/maintenance/settlement-service-item/${currentMaintenanceOrderId.value}/${currentMaintenanceOrderSettlementRow.value.id}`;let fileName = `${currentMaintenanceOrder.value.title} ${currentMaintenanceOrderSettlementRow.value.nYearAndMonth} 第【${currentMaintenanceOrderSettlementRow.value.payNum}】期结算服务清单.xlsx`;let tokenData = getToken();var xhr = new XMLHttpRequest();xhr.open("get", url, true); // get、post都可xhr.responseType = "blob"; // 转换流xhr.setRequestHeader("Authorization", formatToken(tokenData.accessToken)); // token键值对xhr.onload = function () {if (this.status == 200) {var blob = this.response;var a = document.createElement("a");var url = window.URL.createObjectURL(blob);a.href = url;a.download = fileName; // 文件名}a.click();window.URL.revokeObjectURL(url);exportLoading.value = false;};xhr.send();
};
后端代码
在后端建一个控制器,控制器方法代码如下:
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
/// <summary>
/// 导出结算服务项
/// </summary>
/// <param name="maintenanceOrderId"></param>
/// <param name="maintenanceOrderSettlementId"></param>
/// <returns></returns>
[HttpGet]
[Route("settlement-service-item/{maintenanceOrderId}/{maintenanceOrderSettlementId}")]
public async Task<FileResult> ExportMaintenanceOrderSettlementServiceItemsExcelAsync(Guid maintenanceOrderId, Guid maintenanceOrderSettlementId)
{var title = $"{maintenanceOrderSettlementId}.xlsx";var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";//octet-streamvar workbook = await _maintenanceOrderServiceItemAppService.GetExportMaintenanceOrderSettlementServiceItemsExcelAsync(maintenanceOrderId, maintenanceOrderSettlementId);var bytes = workbook.ConvertToBytes();if (bytes != null){// 设置响应头var cd = new System.Net.Mime.ContentDisposition{Inline = false,FileName = $"{title}", // 指定下载的文件名CreationDate = DateTime.Now};// 添加必须的响应头Response.ContentType = contentType;Response.Headers.Add("Content-Disposition", cd.ToString());// 返回文件流return File(bytes, contentType,title,true);}return null;}