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

官网

相关推荐
*长铗归来*1 天前
ASP.NET Core Web API 中控制器操作的返回类型及Swagger
后端·c#·asp.net·.netcore
IDOlaoluo1 天前
VS2017 安装 .NET Core 2.2 SDK 教程(包括 dotnet-sdk-2.2.108-win-x64.exe 安装步骤)
.netcore
csdn_aspnet9 天前
使用 Entity Framework Code First 方法创建 ASP.NET Core 5.0 Web API
.netcore·webapi
小先生8129 天前
.NET Core项目中 Serilog日志文件配置
c#·.netcore
爱吃香蕉的阿豪9 天前
.NET Core 中 System.Text.Json 与 Newtonsoft.Json 深度对比:用法、性能与场景选型
数据库·json·.netcore
csdn_aspnet9 天前
ASP.NET Core 10.0 的主要变化
.netcore
csdn_aspnet12 天前
在 C# .NETCore 中使用 MongoDB(第 1 部分):驱动程序基础知识和插入文档
mongodb·.netcore
csdn_aspnet12 天前
在 C# .NETCore 中使用 MongoDB(第 3 部分):跳过、排序、限制和投影
mongodb·c#·.netcore
csdn_aspnet13 天前
在 C# .NETCore 中使用 MongoDB(第 2 部分):使用过滤子句检索文档
mongodb·c#·.netcore
csdn_aspnet16 天前
.NET Core 中 RabbitMQ 和 MassTransit 的使用
rabbitmq·.netcore·masstransit