.NET CORE 2.1 导出excel文件的两种方法

最近在做 MVC 项目的时候遇到项目的导出,下面总结下两种导出到excel 的方法

第一种方法: 将文件写到本地,然后返回这个File 或者返回这个 File 的绝对地址

   其中  _hostingEnvironment  可以在全局读取的配置文件的工具类 Globals 中配置

   直接上代码:

private IHostingEnvironment _hostingEnvironment; public XlsxController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } public IActionResult ExportData(int programmeId) { //获取方案名称 var programmeName = ProgrammeService.GetProgrammeNameById(programmeId); //获取列表内容 var dataFromDb = ProgrammeService.GetProgrammeStatisticEnrolmentExportList(programmeId); var data = dataFromDb.Select(a => new ProgrammeStatisticsEnrolmentDetailsExportViewModel { UserName = a.UserName, Phone = a.Phone, EnrolTime = a.EnrolTimeStr }).ToList(); var sWebRootFolder = _hostingEnvironment.WebRootPath; var sFileName = $"XXX-{programmeName}.xlsx"; var file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); using (var package = new ExcelPackage(file)) { //如果之前有同名的文件先删除然后重新创建 var count = package.Workbook.Worksheets.Count; if (count > 0) { for (var i = 0; i < count; i++) { package.Workbook.Worksheets.Delete(i + 1); } package.File.Delete(); } // 添加worksheet ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1"); //添加头 worksheet.Cells[1, 1].Value = "姓名"; worksheet.Cells[1, 2].Value = "手机号"; worksheet.Cells[1, 3].Value = "报名时间"; //添加值 for (var i = 0; i < data.Count; i++) { worksheet.Cells[$"A{i + 2}"].Value = data[i].UserName; worksheet.Cells[$"B{i + 2}"].Value = data[i].Phone; worksheet.Cells[$"C{i + 2}"].Value = data[i].EnrolTime; } package.Save(); } var returnFile = File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); returnFile.FileDownloadName = sFileName; return returnFile; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpswwg.html