.net core NPOI以及NOPI mapper

我们在日常开发中对Excel的操作可能会比较频繁,好多功能都会涉及到Excel的操作。在.Net Core中大家可能使用Npoi比较多,这款软件功能也十分强大,而且接近原始编程。但是直接使用Npoi大部分时候我们可能都会自己封装一下,毕竟根据二八原则,我们百分之八十的场景可能都是进行简单的导入导出操作,这里就引出我们的主角Npoi.Mapper了。

  1. 引入包
    需要注意二者对版本要求很高需要"对应"
bash 复制代码
<PackageReference Include="NPOI" Version="2.5.6" />
<PackageReference Include="Npoi.Mapper" Version="4.1.0" />
  1. 定义实体类
csharp 复制代码
    public class Person
    {
        [Column("姓名")]//对应excel中的列名就是姓名
        public string Name { get; set; }

        [Column("年龄")]
        public int Age { get; set; }

        [Column("出生日期", CustomFormat = "yyyy/MM/dd")]
        public DateTime Birthday { get; set; }
    }
  1. 导入
csharp 复制代码
[HttpPost]
public async Task<List<Person>> Upload(IFormFile formFile)
{
    var mapper = new Mapper(formFile.OpenReadStream());

    List<Person>  persons = mapper.Take<Person>("sheet1").Select(x=>x.Value).ToList();

    return persons;
}
  1. 输出文件流
csharp 复制代码
[HttpGet]
public ActionResult DownLoadFile()
{
    List<Person> persons = new List<Person>
    {
        new Person(){Name = "hhh",Age=100,Birthday=new DateTime(1990,11,11)}
    };

    var mapper = new Mapper();
    MemoryStream stream = new MemoryStream();
    //将students集合生成的Excel直接放置到Stream中
    mapper.Save(stream, persons, "sheet1", overwrite: true, xlsx: true);
    return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "person.xlsx");
}
  1. 忽略操作
    有时候我们的导出或导入数据可能想忽略某些列不导出,Npoi.Mapper为了我们提供了类似EF的Ignore操作,这样的话无论是导入还是导出都会忽略这个属性,即导出不会显示这个列,导入不会映射这一列的数据
csharp 复制代码
[Ignore]
public string IgnoredProperty { get; set; }
  1. 合并单元格
    如果我们导入的数据有一列数据的值是大家都拥有的,在Excel上可以通过合并单元格的操作来显示这一列,对于合并单元格的列,对于程序来讲就是等价于所有列都是同一个值,Npoi.Mapper为我们做了这种处理
csharp 复制代码
[UseLastNonBlankValue]
public string ClassName { get; set; }

官网

相关推荐
时光追逐者5 天前
C#/.NET/.NET Core技术前沿周刊 | 第 49 期(2025年8.1-8.10)
c#·.net·.netcore
切糕师学AI5 天前
在 .NET Core 5.0 中启用 Gzip 压缩 Response
.netcore
周杰伦fans6 天前
.NET Core MVC中CSHTML
mvc·.netcore
爱吃香蕉的阿豪13 天前
乐思 AI 智能识别平台(基于 YOLO,.NET+Vue3 开发)开源指南
人工智能·yolo·开源·aigc·.netcore
时光追逐者13 天前
C#/.NET/.NET Core优秀项目和框架2025年7月简报
c#·.net·.netcore
步、步、为营19 天前
.NET Core 3.1 升级到 .NET 8
microsoft·.net·.netcore
时光追逐者20 天前
C#/.NET/.NET Core技术前沿周刊 | 第 48 期(2025年7.21-7.27)
c#·.net·.netcore·.net core
爱吃香蕉的阿豪21 天前
SignalR 全解析:核心原理、适用场景与 Vue + .NET Core 实战
vue.js·microsoft·c#·.netcore·signalr
工藤新一OL22 天前
把xml的格式从utf-8-bom转为utf-8
xml·c#·asp.net·.netcore·visual studio
王柏龙23 天前
Asp.net core mvc中TagHelper的GetChildContentAsync和Content区别
mvc·.netcore