最近没什么时间,主线剧情是玩不来了,所以偷个懒,打一个直线任务。 如果我们的程序对操作Excel有需求,那么NPOI应该不会陌生。不过这里并不打算说NPOI,而是另外一个使用简单的工具:MiniExcel https://gitee.com/dotnetchina/MiniExcel MiniExcel简单、高效避免OOM的.NET处理Excel查、写、填充数据工具。 目前主流框架大多需要将数据全载入到内存方便操作,但这会导致内存消耗问题,MiniExcel 尝试以 Stream 角度写底层算法逻辑,能让原本1000多MB占用降低到几MB,避免内存不够情况。 特点
上面是关于MiniExcel的简单介绍,下面开始实战。 我这里新建一个WPF项目,添加一个DataGrid用于显示数据。 绑定Students数据,
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方法;
我们可以看到,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方法。
注意我们这里的overwriteFile:true 如果不设定覆盖文件,那么当student.xlsx存在,那么就引发IO异常 |
|
来自: 新用户0118F7lQ > 《文件夹1》