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

官网

相关推荐
刘梦凡呀2 天前
C# .NET Core 批量下载文件
windows·c#·.netcore
Zhen (Evan) Wang2 天前
.NET 6 WPF 利用CefSharp.Wpf.NETCore显示PDF文件
.net·wpf·.netcore
时光追逐者2 天前
C#/.NET/.NET Core拾遗补漏合集(25年4月更新)
c#·.net·.netcore
追雨潮3 天前
.net core 项目快速接入Coze智能体-开箱即用-第2节
.netcore
追雨潮3 天前
.net core 项目快速接入Coze智能体-开箱即用-全局说明
.netcore·ai编程
时光追逐者4 天前
C#/.NET/.NET Core技术前沿周刊 | 第 35 期(2025年4.14-4.20)
c#·.net·.netcore
全栈小54 天前
【C#】.net core 6.0调用MVC API接口时,提示Unsupported Media Type,状态码415
c#·mvc·.netcore
猫霸4 天前
理解.NET Core中的配置Configuration
html·.netcore·xhtml
MoFe14 天前
【.net core】【watercloud】数据库连接报错问题
数据库·.netcore
csdn_aspnet4 天前
Windows .NET Core 应用程序部署到 IIS 解决首次访问加载慢的问题
iis·.netcore