最近没什么时间,主线剧情是玩不来了,所以偷个懒,打一个直线任务。如果我们的程序对操作Excel有需求,那么NPOI应该不会陌生。不过这里并不打算说NPOI,而是另外一个使用简单的工具:MiniExcel
项目地址:
https://gitee.com/dotnetchina/MiniExcel
MiniExcel简单、高效避免OOM的.NET处理Excel查、写、填充数据工具。
目前主流框架大多需要将数据全载入到内存方便操作,但这会导致内存消耗问题,MiniExcel 尝试以 Stream 角度写底层算法逻辑,能让原本1000多MB占用降低到几MB,避免内存不够情况。
特点
1.低内存耗用,避免OOM、频繁 Full GC 情况
2.支持即时操作每行数据
3.兼具搭配 LINQ 延迟查询特性,能办到低消耗、快速分页等复杂查询
4.轻量,不需要安装 Microsoft Office、COM+,DLL小于150KB
5.简便操作的 API 风格
上面是关于MiniExcel的简单介绍,下面开始实战。
我这里新建一个WPF项目,添加一个DataGrid用于显示数据。
绑定Students数据,
private List<StudentInfo> students;
public List<StudentInfo> Students { get => students; set => SetProperty(ref students, value); }
StudentInfo类属性如下:
public class StudentInfo
{
public string Name { get; set; }
public string Age { get; set; }
public string Grade { get; set; }
}
新建一个xlsx表格,数据如下,title与StudentInfo对应
通过Nuget加载MiniExcel。
当我们需要读取数据,使用Query方法;
string filePath = Path.Combine(AppContext.BaseDirectory, "students.xlsx");
Students = MiniExcel.Query<StudentInfo>(filePath).ToList();
我们可以看到,MiniExcel使用的是静态方法,返回的数据是IEnumerable
public static IEnumerable<T> Query<T>(string path, string sheetName = null, ExcelType excelType = ExcelType.UNKNOWN, string startCell = "A1", IConfiguration configuration = null) where T : class, new()
{
using FileStream stream = FileHelper.OpenSharedRead(path);
foreach (T item in stream.Query<T>(sheetName, ExcelTypeHelper.GetExcelType(path, excelType), startCell, configuration))
{
yield return item;
}
}
当我们转换为List,就可以进行更多的处理。
将数据写入Excel,使用SaveAS方法。
Students = new List<StudentInfo>
{
new StudentInfo() { Name="熏儿",Age="25",Grade="斗帝"},
new StudentInfo() { Name="小医仙",Age="24",Grade="斗帝"},
};
string filePath = Path.Combine(AppContext.BaseDirectory, "students.xlsx");
MiniExcel.SaveAs(filePath, Students,overwriteFile:true);
注意:我们这里的overwriteFile:true
如果不设定覆盖文件,那么当student.xlsx存在,那么就引发IO异常