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

官网

相关推荐
神仙别闹21 小时前
基于 .Net Core+MySQL开发(WinForm)翻译平台
数据库·mysql·.netcore
孤的心了不冷1 天前
【后端】.NET Core API框架搭建(9) --配置使用Log4Net日志
后端·.netcore
孤的心了不冷2 天前
【后端】配置SqlSugar ORM框架并添加仓储
mysql·sqlserver·.netcore
时光追逐者3 天前
C#/.NET/.NET Core技术前沿周刊 | 第 46 期(2025年7.7-7.13)
c#·.net·.netcore
王柏龙3 天前
aspnetcore Mvc配置选项中的ModelMetadataDetailsProviders
mvc·.netcore
江沉晚呤时4 天前
在 C# 中调用 Python 脚本:实现跨语言功能集成
python·microsoft·c#·.net·.netcore·.net core
喵叔哟5 天前
3. 【Blazor全栈开发实战指南】--Blazor是什么?为什么选择Blazor?
c#·.netcore
deriva14 天前
.netcore+ef+redis+rabbitmq+dotcap先同步后异步再同步的方法,亲测有效
redis·rabbitmq·.netcore
棉晗榜1 个月前
C# .net core添加单元测试项目,依赖注入接口测试
单元测试·c#·.netcore
时光追逐者1 个月前
.NET初级软件工程师面试经验分享
经验分享·面试·职场和发展·c#·.net·.netcore