首页 > 编程语言 >Asp.NET Core 导出数据到 Excel 文件

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

时间:2023-02-23 19:00:21浏览次数:45  
标签:Core Asp Excel entity entities CreateCell var SetCellValue row

在Asp.Net Core开发中,使用NPOI将数据导出到Excel文件中,并返回给前端。

service 层代码:

        /// <summary>
        /// 将数据导出到excel
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<IWorkbook> ExportToExcel(Guid projectId, List<Guid> ids = null)
        {
            var entities = await attendanceRecordRepository.Find(x =>
                                                x.ProjectId == projectId)
                                                .ToListAsync();

            if (entities == null || entities.Count == 0) return null;

            //创建工作簿
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("考勤记录");

            //添加表头
            IRow tableHeader = sheet.CreateRow(0);
            var colNames = new List<string>()
            {
                "姓名", "身份证号", "工号", "人员类型", "办公室", "工种", "电话号码", "状态", "打卡时间"
            };
            for (int i = 0; i < colNames.Count; i++)
            {
                tableHeader.CreateCell(i).SetCellValue(colNames[i]);
                // 自适应宽高
                sheet.AutoSizeColumn(i);
            }

            // 将数据写入表格中
            if (ids == null || ids.Count == 0)
            {
                // 导出全部
                for (int i = 0; i < entities.Count; i++)
                {
                    // 跳过表头
                    var row = sheet.CreateRow(i + 1);

                    row.CreateCell(0).SetCellValue(entities[i].Name);
                    row.CreateCell(1).SetCellValue(entities[i].ID_card);
                    row.CreateCell(2).SetCellValue(entities[i].EmployeeNumber);
                    row.CreateCell(3).SetCellValue(entities[i].PersonnelType);
                    row.CreateCell(4).SetCellValue(entities[i].OfficeLocation);
                    row.CreateCell(5).SetCellValue(entities[i].PostName);
                    row.CreateCell(6).SetCellValue(entities[i].PhoneNumber);
                    row.CreateCell(7).SetCellValue(entities[i].Type);
                    row.CreateCell(8).SetCellValue(entities[i].CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                }
            }
            else
            {
                // 导出部分
                int rowIndex = 1;
                foreach (var entity in entities)
                {
                    foreach (var id in ids)
                    {
                        if (entity.Id == id)
                        {
                            var row = sheet.CreateRow(rowIndex);

                            row.CreateCell(0).SetCellValue(entity.Name);
                            row.CreateCell(1).SetCellValue(entity.ID_card);
                            row.CreateCell(2).SetCellValue(entity.EmployeeNumber);
                            row.CreateCell(3).SetCellValue(entity.PersonnelType);
                            row.CreateCell(4).SetCellValue(entity.OfficeLocation);
                            row.CreateCell(5).SetCellValue(entity.PostName);
                            row.CreateCell(6).SetCellValue(entity.PhoneNumber);
                            row.CreateCell(7).SetCellValue(entity.Type);
                            row.CreateCell(8).SetCellValue(entity.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));

                            rowIndex++;
                        }
                    }
                }
            }

            return workbook;
        }

controller 层代码: 

        /// <summary>
        /// 将数据导出为Excel文件
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("export-to-excel")]
        public async Task<IActionResult> ExportToExcel(Guid projectId, List<Guid> ids = null)
        {
            var workbook = await _attendanceRecordService.ExportToExcel(projectId, ids);

            if(workbook != null)
            {
                var path = Path.Combine(webHostEnvironment.ContentRootPath, "FileName");
                if (!Directory.Exists(path)) //没有此路径就新建
                {
                    Directory.CreateDirectory(path);
                }
                var fileFullName = Path.Combine(path, $"{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}.xlsx");

                // 将表格写入文件流
                FileStream creatStream = new FileStream(fileFullName, FileMode.Create, FileAccess.Write);
                workbook.Write(creatStream);
                creatStream.Close();

                // 将表格文件转换成可读的文件流
                FileStream fileStream = new FileStream(fileFullName, FileMode.Open, FileAccess.Read, FileShare.Read); //读

                // 将可读文件流写入 byte[]
                byte[] bytes = new byte[fileStream.Length];
                fileStream.Read(bytes, 0, bytes.Length);
                fileStream.Close();

                // 把 byte[] 转换成 Stream (创建其支持存储区为内存的流。)
                MemoryStream stream = new(bytes);

                try
                {
                    return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                            $"{DateTime.Now.ToString("yyyyMMddHHmmss")}考勤记录");
                }
                finally
                {
                    System.IO.File.Delete(fileFullName);
                }
                
            }
            return BadRequest();
        }

 

标签:Core,Asp,Excel,entity,entities,CreateCell,var,SetCellValue,row
From: https://www.cnblogs.com/rockrose/p/17149093.html

相关文章

  • asp.net core webapi初识
    1.建立webapi项目  2.把启用SSL取消勾选(取消https)  3.选择项目-右键-发布,进行发布信息设置,选择文件夹发布   4.打开IIS管理器,新建网站,物理路径选择刚刚......
  • 使用 pm2 守护你的 .NET Core 应用程序
    一.守护进程的前世今生#守护进程,英文名:“daemon",也有守护神的意思。守护进程是一个在后台运行并且不受任何终端控制的进程,不会随着会话结束而退出。诸如mysql、apache等......
  • ASP.NET 使用HTTP请求代理提示错误: The SSL connection could not be established, s
    在 HttpClientHandler 当中会有一个 ServerCertificateCustomValidationCallback 事件,该事件用于判定证书验证是否通过。我们可以挂接该事件,然后逻辑编写为直接返回 t......
  • Interop.Excel 个人总结(一)
    第一步,点击项目,管理nuget程序包,浏览Microsoft.Office.Interop.Excel   第二步,创建一个应用程序Microsoft.Office.Interop.Excel.Applicationapp =newMicrosoft......
  • metasploit2-practice-cnblog
    Metasploittable2打靶教程本次靶机练习主要熟悉:高危端口利用;metasploit中search,show及各个模块使用。一、环境准备1.把靶场放在vmware打开,启用nat模式:2.启用kali......
  • 如何将Excel文档转换为PDF文档
    当需要储存或者编辑大量数据时,Excel确实是绝佳的选择。但如果想要将编辑好的数据内容更好的保存或者发送给他人参考的话,PDF文档格式可能更加适合。今天我想分享的是如何通......
  • Excel 相关
    Excel公式引用当前单元格左侧单元格引用当前单元格左侧的第一个单元格:=OFFSET(INDIRECT(ADDRESS(ROW(),COLUMN())),0,-1)。ROW()返回当前单元格的行号,COLUMN()返回当......
  • 【C#进阶】.NET Core 中的筛选器 Filter【ActionFilterAttribute 操作筛选器,实现日志
     筛选器Filter介绍:【C#进阶】.NETCore中的筛选器Filter-C#初级程序员-博客园(cnblogs.com) ActionFilterAttribute操作筛选器,实现日志记录第一步创建.NE......
  • docker 本地linux环境调试 .net 代码 —— debugging dockerized .NET core applicat
    原文:HowtoDebugDockerized.NETCoreAppsinVSCode(freecodecamp.org) vscoderundockercommand:dockerimagebuild--pull--file"C:\[path]/[projectN......
  • Net Core 3.1 ONVIF 操控海康摄像头
    先给出实现的代码https://github.com/lu1770/onvif-client.git这里实现了设备发现,登录,获得码流列表,获得画面rtsp,vlc播放,云台上下左右控制,放大缩小安装nuget包......