ASP.Net Core 2.0实现Excel导出至客户端的方法咨询
我来帮你搞定这个问题——在ASP.NET Core 2.0里,不管是替代原来ASP.NET MVC那种HTML转Excel的导出逻辑,还是解决NPOI生成Excel后推送到客户端的问题,都有清晰的方案,咱们一步步说:
一、替代原来的HTML导出Excel逻辑
原来的ASP.NET MVC里直接操作Response的方式在Core里不再适用,但我们可以用Core原生的FileResult来实现相同的效果,本质还是让浏览器把HTML内容识别为Excel文件并触发下载:
public IActionResult ExportHtmlToExcel() { // 替换成你实际要导出的HTML内容(对应原来的ExportDiv.InnerHtml) string exportHtml = "<table><thead><tr><th>姓名</th><th>部门</th></tr></thead><tbody><tr><td>张三</td><td>技术部</td></tr><tr><td>李四</td><td>市场部</td></tr></tbody></table>"; // 将HTML转为字节数组 byte[] htmlBytes = Encoding.UTF8.GetBytes(exportHtml); // 返回文件流,指定ContentType和下载文件名 return File( fileContents: htmlBytes, contentType: "application/vnd.ms-excel", fileDownloadName: "ExportedHtml.xls" ); }
调用这个Action后,浏览器会自动弹出保存对话框,和你原来的代码效果完全一致。
二、用NPOI生成Excel并推送到客户端
你说NPOI能正常生成Excel但没法保存到客户端,其实是没把生成的工作簿转换成可下载的流。只需要把NPOI的IWorkbook写入内存流,再通过FileResult返回即可:
using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.IO; public IActionResult ExportWithNPOI() { // 创建XLSX格式的工作簿(如果要生成XLS格式,改用HSSFWorkbook) IWorkbook workbook = new XSSFWorkbook(); ISheet dataSheet = workbook.CreateSheet("员工数据"); // 构建表头 IRow headerRow = dataSheet.CreateRow(0); headerRow.CreateCell(0).SetCellValue("姓名"); headerRow.CreateCell(1).SetCellValue("部门"); // 填充数据行 IRow dataRow1 = dataSheet.CreateRow(1); dataRow1.CreateCell(0).SetCellValue("张三"); dataRow1.CreateCell(1).SetCellValue("技术部"); IRow dataRow2 = dataSheet.CreateRow(2); dataRow2.CreateCell(0).SetCellValue("李四"); dataRow2.CreateCell(1).SetCellValue("市场部"); // 将工作簿写入内存流 using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Position = 0; // 重置流的读取位置到开头 // 返回XLSX文件,注意对应的ContentType return File( fileContents: ms.ToArray(), contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileDownloadName: "ExportedNPOI.xlsx" ); } }
这样返回后,浏览器同样会弹出保存对话框,用户可以选择保存位置,完美解决你的问题。
额外说明:如果一定要直接操作Response(不推荐)
虽然Core更推荐用IActionResult的方式返回,但如果你想模拟原来直接操作Response的逻辑,也可以这么做(注意异步场景下要使用async/await):
public async Task<IActionResult> ExportViaResponse() { string exportHtml = "<table><tr><td>测试数据</td></tr></table>"; byte[] htmlBytes = Encoding.UTF8.GetBytes(exportHtml); // 设置响应头 Response.Headers.Add("Content-Disposition", "attachment; filename=ExportedHtml.xls"); Response.ContentType = "application/vnd.ms-excel"; // 写入响应流 await Response.Body.WriteAsync(htmlBytes); return new EmptyResult(); }
不过还是优先推荐前面两种FileResult的方式,更符合ASP.NET Core的设计规范。
内容的提问来源于stack exchange,提问作者Tanwer
相关产品推荐
相关产品推荐

