分享

MiniExcel:一个非常高效的Excel读写工具

 新用户0118F7lQ 2023-09-02 发布于山东

最近没什么时间,主线剧情是玩不来了,所以偷个懒,打一个直线任务。

如果我们的程序对操作Excel有需求,那么NPOI应该不会陌生。不过这里并不打算说NPOI,而是另外一个使用简单的工具:MiniExcel

https://gitee.com/dotnetchina/MiniExcel

MiniExcel简单、高效避免OOM的.NET处理Excel查、写、填充数据工具。

目前主流框架大多需要将数据全载入到内存方便操作,但这会导致内存消耗问题,MiniExcel 尝试以 Stream 角度写底层算法逻辑,能让原本1000多MB占用降低到几MB,避免内存不够情况。

图片

特点

  • 低内存耗用,避免OOM、频繁 Full GC 情况

  • 支持即时操作每行数据

  • 兼具搭配 LINQ 延迟查询特性,能办到低消耗、快速分页等复杂查询

  • 轻量,不需要安装 Microsoft Office、COM+,DLL小于150KB

  • 简便操作的 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异常

图片

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多