后端使用NPOI返回文件流前端将其导出下载在浏览器
中打开的方法如下:
后端代码:
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using System.Web;
using System.Web.Mvc;
public class HomeController : Controller
{
public ActionResult ExportExcel()
{
// 创建Excel文件
IWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");
sheet.CreateRow(0).CreateCell(0).SetCellValue("Hello World!");
// 将Excel文件转换为字节数组
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
byte[] bytes = ms.ToArray();
// 将字节数组返回给前端
return File(bytes, "application/vnd.ms-excel", "test.xls");
}
}
前端代码:
function exportExcel() {
$.ajax({
url: "/Home/ExportExcel",
type: "POST",
dataType: "binary",
processData: false,
success: function (result) {
var blob = new Blob([result], { type: "application/vnd.ms-excel" });
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = "test.xls";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
},
error: function (xhr, status, error) {
console.log(xhr);
}
});
}
注意事项:
- 后端返回的文件流需要设置Content-Type为"application/vnd.ms-excel",否则前端无法识别文件类型。
- 前端通过创建Blob对象和URL.createObjectURL方法将字节数组转换为URL,然后通过创建a标签模拟点击下载。
原文地址: https://www.cveoy.top/t/topic/7Gz 著作权归作者所有。请勿转载和采集!