Asp .Net Core Excel导入和导出
ASP .Net Core使用EPPlus实现Api导入导出,这里使用是EPPlus 4.5.2.1版本,.Net Core 2.2。在linux上运行的时候需要安装libgdiplus 。
下面我们看下如何实现导出导入的功能。
新建项目ASP.NET Core Web Api 、添加Test类
public class Test { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; }
}
导出Excel文件
新建控制器ExecelController
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using OfficeOpenXml; namespace WebApplication5.Controllers { [ApiController] public class ExecelController : ControllerBase { [Route("api/Execel/TOExecel")] public IActionResult TOExecel() { var list = new List<Test>(); list.Add(new Test() { Id = 1, Name = "Test", Age = 22, }); byte[] fileContents; using (ExcelPackage package = new ExcelPackage()) { ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(".Net Core 导出"); worksheet.Cells[1, 1].Value = "序号"; worksheet.Cells[1, 2].Value = "Id"; worksheet.Cells[1, 3].Value = "名称"; worksheet.Cells[1, 4].Value = "年龄"; int i = 2; foreach (var item in list) { worksheet.Cells["A" + i].Value = i - 1; worksheet.Cells["B" + i].Value = item.Id; worksheet.Cells["C" + i].Value = item.Name; worksheet.Cells["D" + i].Value = item.Age; i = i + 1; } fileContents = package.GetAsByteArray(); if (fileContents == null || fileContents.Length == 0) { return NotFound(); } } return File(fileContents, "application/ms-excel", $"{Guid.NewGuid().ToString()}.xlsx"); } } }
导入Excel文件
[Route("api/Execel/Import")] public async Task<IActionResult> Import(IFormFile excelFile) { var msg = ""; if (excelFile == null || excelFile.Length <= 0) { msg = "请选择导入文件!"; return Ok(msg); } if (!Path.GetExtension(excelFile.FileName).Equals(".xlsx", StringComparison.OrdinalIgnoreCase)) { msg = "请选择导入文件为.xlsx的后缀名!"; return Ok(msg); } try { using (var stream = new MemoryStream()) { await excelFile.CopyToAsync(stream); using (var package = new ExcelPackage(stream)) { StringBuilder sb = new StringBuilder(); ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; int rowCount = worksheet.Dimension.Rows; int ColCount = worksheet.Dimension.Columns; bool bHeaderRow = true; for (int row = 2; row <= rowCount; row++) { Test model = new Test(); for (int col = 1; col <= ColCount; col++) { if (bHeaderRow) { switch (col) { case 1: model.Id = int.Parse(worksheet.Cells[row, col].Value.ToString()); break; case 2: model.Name = worksheet.Cells[row, col].Value.ToString(); break; case 3: model.Age = int.Parse(worksheet.Cells[row, col].Value.ToString()); break; } } else { switch (col) { case 1: model.Id = int.Parse(worksheet.Cells[row, col].Value.ToString()); break; case 2: model.Name = worksheet.Cells[row, col].Value.ToString(); break; case 3: model.Age = int.Parse(worksheet.Cells[row, col].Value.ToString()); break; } } } //插入model即可 } } } msg = "导入成功!"; return Ok(msg); } catch (Exception ex) { msg = ex.Message; return Ok(msg); } }
按照格式导入即可完成导入功能。
这里导出是通过流的方式进行导出的,一般来说也可以先把Excel保存到服务器,然后直接通过Url访问服务器的文件的地址就可以实现在线下载。通过流导出的话就不需要去访问服务器文件了,访问接口查询数据就直接导出了。
在导入的时候目前测试仅仅支持.xlsx格式的,.xls格式的Excel在基于流创建ExcelPackage类的新实例的时候会报为空的错误。var package = new ExcelPackage(stream)还有待修改。
欢迎大家扫描下方二维码,和我一起学习更多的知识😊
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?