在.Net core 使用NPOI首先必须先安装DotNetCore.NPOI,第一种方法可以在管理Nuget包中安装,如图:
引用代码:
using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel;
业务代码:
/// <summary> /// 导出列表 /// </summary> /// <returns></returns> public void GetExportList() { //取出数据源 var exportList = db.Reg_Message .Select(u => new { u.UserName, u.Mobile, u.Content, u.CreateDate }).ToList(); HSSFWorkbook book = new HSSFWorkbook(); ISheet s1 = book.CreateSheet("留言列表"); IRow r1 = s1.CreateRow(0); r1.CreateCell(0).SetCellValue("用户"); r1.CreateCell(1).SetCellValue("手机号"); r1.CreateCell(2).SetCellValue("留言内容"); r1.CreateCell(3).SetCellValue("留言日期"); for (int i = 0; i < exportList.Count; i++) { NPOI.SS.UserModel.IRow rt = s1.CreateRow(i + 1); rt.CreateCell(0).SetCellValue(exportList[i].UserName); rt.CreateCell(1).SetCellValue(exportList[i].Mobile); rt.CreateCell(2).SetCellValue(exportList[i].Content); rt.CreateCell(3).SetCellValue(exportList[i].CreateDate); } var path = ConfigHelper.GetValue("ExportPath"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } FileStream stream = new FileStream(path + DateTime.Now.ToString("yyyyMMddhhmmssffff") + ".xls", FileMode.CreateNew); book.Write(stream); stream.Seek(0, SeekOrigin.Begin); book.Close(); stream.Close(); }
前端代码:
//导出
function btn_export() {
//location.href = "../../RegManage/Message/ExportList";
$.ConfirmAjax({
msg: "注:您确定要导出吗?",
url: "/RegManage/Message/ExportList",
success: function (data) {
$("#gridTable").trigger("reloadGrid");
}
})
}