.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; }

官网

相关推荐
deriva2 天前
.netcore+ef+redis+rabbitmq+dotcap先同步后异步再同步的方法,亲测有效
redis·rabbitmq·.netcore
棉晗榜18 天前
C# .net core添加单元测试项目,依赖注入接口测试
单元测试·c#·.netcore
时光追逐者18 天前
.NET初级软件工程师面试经验分享
经验分享·面试·职场和发展·c#·.net·.netcore
忧郁的蛋~20 天前
.NET Core 实现缓存的预热的方式
缓存·c#·.net·.netcore
csdn_aspnet21 天前
C# .NET Core 源代码生成器(dotnet source generators)
c#·.netcore
时光追逐者21 天前
C#/.NET/.NET Core技术前沿周刊 | 第 42 期(2025年6.9-6.15)
c#·.net·.netcore
csdn_aspnet22 天前
使用 C# 源生成器(Source Generators)进行高效开发:增强 Blazor 及其他功能
c#·.netcore
lgaof65822@gmail.com24 天前
Asp.Net Core SignalR导入数据
前端·后端·asp.net·.netcore
眸笑丶24 天前
.NET Core 数据库连接字符串加密与解密
数据库·oracle·.netcore
时光追逐者1 个月前
C#/.NET/.NET Core技术前沿周刊 | 第 41 期(2025年6.1-6.8)
c#·.net·.netcore