翼度科技»论坛 编程开发 .net 查看内容

Asp.NET Core 导出数据到 Excel 文件

3

主题

3

帖子

9

积分

新手上路

Rank: 1

积分
9
在Asp.Net Core开发中,使用NPOI将数据导出到Excel文件中,并返回给前端。
service 层代码:
  1.         /// <summary>
  2.         /// 将数据导出到excel
  3.         /// </summary>
  4.         /// <param name="projectId"></param>
  5.         /// <param name="ids"></param>
  6.         /// <returns></returns>
  7.         public async Task<IWorkbook> ExportToExcel(Guid projectId, List<Guid> ids = null)
  8.         {
  9.             var entities = await attendanceRecordRepository.Find(x =>
  10.                                                 x.ProjectId == projectId)
  11.                                                 .ToListAsync();
  12.             if (entities == null || entities.Count == 0) return null;
  13.             //创建工作簿
  14.             IWorkbook workbook = new XSSFWorkbook();
  15.             ISheet sheet = workbook.CreateSheet("考勤记录");
  16.             //添加表头
  17.             IRow tableHeader = sheet.CreateRow(0);
  18.             var colNames = new List<string>()
  19.             {
  20.                 "姓名", "身份证号", "工号", "人员类型", "办公室", "工种", "电话号码", "状态", "打卡时间"
  21.             };
  22.             for (int i = 0; i < colNames.Count; i++)
  23.             {
  24.                 tableHeader.CreateCell(i).SetCellValue(colNames[i]);
  25.                 // 自适应宽高
  26.                 sheet.AutoSizeColumn(i);
  27.             }
  28.             // 将数据写入表格中
  29.             if (ids == null || ids.Count == 0)
  30.             {
  31.                 // 导出全部
  32.                 for (int i = 0; i < entities.Count; i++)
  33.                 {
  34.                     // 跳过表头
  35.                     var row = sheet.CreateRow(i + 1);
  36.                     row.CreateCell(0).SetCellValue(entities[i].Name);
  37.                     row.CreateCell(1).SetCellValue(entities[i].ID_card);
  38.                     row.CreateCell(2).SetCellValue(entities[i].EmployeeNumber);
  39.                     row.CreateCell(3).SetCellValue(entities[i].PersonnelType);
  40.                     row.CreateCell(4).SetCellValue(entities[i].OfficeLocation);
  41.                     row.CreateCell(5).SetCellValue(entities[i].PostName);
  42.                     row.CreateCell(6).SetCellValue(entities[i].PhoneNumber);
  43.                     row.CreateCell(7).SetCellValue(entities[i].Type);
  44.                     row.CreateCell(8).SetCellValue(entities[i].CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
  45.                 }
  46.             }
  47.             else
  48.             {
  49.                 // 导出部分
  50.                 int rowIndex = 1;
  51.                 foreach (var entity in entities)
  52.                 {
  53.                     foreach (var id in ids)
  54.                     {
  55.                         if (entity.Id == id)
  56.                         {
  57.                             var row = sheet.CreateRow(rowIndex);
  58.                             row.CreateCell(0).SetCellValue(entity.Name);
  59.                             row.CreateCell(1).SetCellValue(entity.ID_card);
  60.                             row.CreateCell(2).SetCellValue(entity.EmployeeNumber);
  61.                             row.CreateCell(3).SetCellValue(entity.PersonnelType);
  62.                             row.CreateCell(4).SetCellValue(entity.OfficeLocation);
  63.                             row.CreateCell(5).SetCellValue(entity.PostName);
  64.                             row.CreateCell(6).SetCellValue(entity.PhoneNumber);
  65.                             row.CreateCell(7).SetCellValue(entity.Type);
  66.                             row.CreateCell(8).SetCellValue(entity.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
  67.                             rowIndex++;
  68.                         }
  69.                     }
  70.                 }
  71.             }
  72.             return workbook;
  73.         }
复制代码
controller 层代码: 
  1.         /// <summary>
  2.         /// 将数据导出为Excel文件
  3.         /// </summary>
  4.         /// <param name="projectId"></param>
  5.         /// <param name="ids"></param>
  6.         /// <returns></returns>
  7.         [HttpPost("export-to-excel")]
  8.         public async Task<IActionResult> ExportToExcel(Guid projectId, List<Guid> ids = null)
  9.         {
  10.             var workbook = await _attendanceRecordService.ExportToExcel(projectId, ids);
  11.             if(workbook != null)
  12.             {
  13.                 var path = Path.Combine(webHostEnvironment.ContentRootPath, "FileName");
  14.                 if (!Directory.Exists(path)) //没有此路径就新建
  15.                 {
  16.                     Directory.CreateDirectory(path);
  17.                 }
  18.                 var fileFullName = Path.Combine(path, $"{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}.xlsx");
  19.                 // 将表格写入文件流
  20.                 FileStream creatStream = new FileStream(fileFullName, FileMode.Create, FileAccess.Write);
  21.                 workbook.Write(creatStream);
  22.                 creatStream.Close();
  23.                 // 将表格文件转换成可读的文件流
  24.                 FileStream fileStream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read, FileShare.Read); //读
  25.                 // 将可读文件流写入 byte[]
  26.                 byte[] bytes = new byte[fileStream.Length];
  27.                 fileStream.Read(bytes, 0, bytes.Length);
  28.                 fileStream.Close();
  29.                 // 把 byte[] 转换成 Stream (创建其支持存储区为内存的流。)
  30.                 MemoryStream stream = new(bytes);
  31.                 try
  32.                 {
  33.                     return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
  34.                             $"{DateTime.Now.ToString("yyyyMMddHHmmss")}考勤记录");
  35.                 }
  36.                 finally
  37.                 {
  38.                     System.IO.File.Delete(fileFullName);
  39.                 }
  40.                
  41.             }
  42.             return BadRequest();
  43.         }
复制代码
 

来源:https://www.cnblogs.com/rockrose/archive/2023/02/23/17149093.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具