.Net平台上对Excel进行操作主要有两种方式。第一种,把Excel文件看成一个数据库,通过OleDb的方式进行读取与操作;第二种,调用Excel的COM组件。两种方式各有特点。
今天给大家介绍第三种方式:插件方式,目前主流框架大多需要将数据全载入到内存方便操作,但这会导致内存消耗问题,MiniExcel 尝试以 Stream 角度写底层算法逻辑,能让原本1000多MB占用降低到几MB,避免内存不够情况。
MiniExcel简单、高效避免OOM的.NET处理Excel查、写、填充数据工具。

低内存耗用,避免OOM、频繁 Full GC 情况
支持即时操作每行数据
兼具搭配 LINQ 延迟查询特性,能办到低消耗、快速分页等复杂查询
轻量,不需要安装 Microsoft Office、COM+,DLL小于150KB
简便操作的 API 风格
导入、查询 Excel 比较
逻辑 : 以 Test1,000,000x10.xlsx 做基准与主流框架做性能测试,总共 1,000,000 行 * 10 列笔 "HelloWorld",文件大小 23 MB。

导出、创建 Excel 比较
逻辑 : 创建1千万笔 "HelloWorld"

使用示例
1.1 Query 查询 Excel 返回强型别 IEnumerable 数据
- public class UserAccount
- {
- public Guid ID { get; set; }
- public string Name { get; set; }
- public DateTime BoD { get; set; }
- public int Age { get; set; }
- public bool VIP { get; set; }
- public decimal Points { get; set; }
- }
-
- var rows = MiniExcel.Query
(path); - // or
-
- using (var stream = File.OpenRead(path))
- var rows = stream.Query
();

1.2 Query 查询支援延迟加载(Deferred Execution),能配合LINQ First/Take/Skip办到低消耗、高效率复杂查询
- var row = MiniExcel.Query(path).First();
- Assert.Equal("HelloWorld", row.A);
-
- // or
-
- using (var stream = File.OpenRead(path))
- {
- var row = stream.Query().First();
- Assert.Equal("HelloWorld", row.A);
- }
与其他框架效率比较 :

1.3 读取大文件硬盘缓存 (Disk-Base Cache - SharedString)
概念 : MiniExcel 当判断文件 SharedString 大小超过 5MB,预设会使用本地缓存,如 10x100000.xlsx(一百万笔数据),读取不开启本地缓存需要最高内存使用约195MB,开启后降为65MB。但要特别注意,此优化是以时间换取内存减少,所以读取效率会变慢,此例子读取时间从 7.4 秒提高到 27.2 秒,假如不需要能用以下代码关闭硬盘缓存
- var config = new OpenXmlConfiguration { EnableSharedStringCache = false };
- MiniExcel.Query(path,configuration: config)
也能使用 SharedStringCacheSize 调整 sharedString 文件大小超过指定大小才做硬盘缓存
- var config = new OpenXmlConfiguration { SharedStringCacheSize=500*1024*1024 };
- MiniExcel.Query(path, configuration: config);


2、写/导出 Excel
必须是非abstract 类别有公开无参数构造函数
MiniExcel SaveAs 支援 IEnumerable参数延迟查询,除非必要请不要使用 ToList 等方法读取全部数据到内存

2.1 支持集合<匿名类别>或是<强型别>
var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.xlsx");MiniExcel.SaveAs(path, new[] { new { Column1 = "MiniExcel", Column2 = 1 }, new { Column1 = "Github", Column2 = 2}});
2.2 IDataReader
推荐使用,可以避免载入全部数据到内存

推荐 DataReader 多表格导出方式(建议使用 Dapper ExecuteReader )
- using (var cnn = Connection)
- {
- cnn.Open();
- var sheets = new Dictionary<string,object>();
- sheets.Add("sheet1", cnn.ExecuteReader("select 1 id"));
- sheets.Add("sheet2", cnn.ExecuteReader("select 2 id"));
- MiniExcel.SaveAs("Demo.xlsx", sheets);
- }
3、模板填充 Excel
宣告方式类似 Vue 模板 {{变量名称}}, 或是集合渲染 {{集合名称.栏位名称}}
集合渲染支持 IEnumerable/DataTable/DapperRow
3.1 基本填充

- // 1. By POCO
- var value = new
- {
- Name = "Jack",
- CreateDate = new DateTime(2021, 01, 01),
- VIP = true,
- Points = 123
- };
- MiniExcel.SaveAsByTemplate(path, templatePath, value);
- // 2. By Dictionary
- var value = new Dictionary<string, object>()
- {
- ["Name"] = "Jack",
- ["CreateDate"] = new DateTime(2021, 01, 01),
- ["VIP"] = true,
- ["Points"] = 123
- };
- MiniExcel.SaveAsByTemplate(path, templatePath, value);
3.2 复杂数据填充

- // 1. By POCO
- var value = new
- {
- title = "FooCompany",
- managers = new[] {
- new {name="Jack",department="HR"},
- new {name="Loan",department="IT"}
- },
- employees = new[] {
- new {name="Wade",department="HR"},
- new {name="Felix",department="HR"},
- new {name="Eric",department="IT"},
- new {name="Keaton",department="IT"}
- }
- };
- MiniExcel.SaveAsByTemplate(path, templatePath, value);
- // 2. By Dictionary
- var value = new Dictionary<string, object>()
- {
- ["title"] = "FooCompany",
- ["managers"] = new[] {
- new {name="Jack",department="HR"},
- new {name="Loan",department="IT"}
- },
- ["employees"] = new[] {
- new {name="Wade",department="HR"},
- new {name="Felix",department="HR"},
- new {name="Eric",department="IT"},
- new {name="Keaton",department="IT"}
- }
- };
- MiniExcel.SaveAsByTemplate(path, templatePath, value);
4、Excel 列属性 (Excel Column Attribute)
4.1 指定列名称、指定第几列、是否忽略该列

- public class ExcelAttributeDemo
- {
- [ExcelColumnName("Column1")]
- public string Test1 { get; set; }
- [ExcelColumnName("Column2")]
- public string Test2 { get; set; }
- [ExcelIgnore]
- public string Test3 { get; set; }
- [ExcelColumnIndex("I")] // 系统会自动转换"I"为第8列
- public string Test4 { get; set; }
- public string Test5 { get; } //系统会忽略此列
- public string Test6 { get; private set; } //set非公开,系统会忽略
- [ExcelColumnIndex(3)] // 从0开始索引
- public string Test7 { get; set; }
- }
- var rows = MiniExcel.Query<ExcelAttributeDemo>(path).ToList();
- Assert.Equal("Column1", rows[0].Test1);
- Assert.Equal("Column2", rows[0].Test2);
- Assert.Null(rows[0].Test3);
- Assert.Equal("Test7", rows[0].Test4);
- Assert.Null(rows[0].Test5);
- Assert.Null(rows[0].Test6);
- Assert.Equal("Test4", rows[0].Test7);
4.2 DynamicColumnAttribute 动态设定 Column
- var config = new OpenXmlConfiguration
- {
- DynamicColumns = new DynamicExcelColumn[] {
- new DynamicExcelColumn("id"){Ignore=true},
- new DynamicExcelColumn("name"){Index=1,Width=10},
- new DynamicExcelColumn("createdate"){Index=0,Format="yyyy-MM-dd",Width=15},
- new DynamicExcelColumn("point"){Index=2,Name="Account Point"},
- }
- };
- var path = PathHelper.GetTempPath();
- var value = new[] { new { id = 1, name = "Jack", createdate = new DateTime(2022, 04, 12) ,point = 123.456} };
- MiniExcel.SaveAs(path, value, configuration: config);

MiniExcel 预设会根据文件扩展名判断是 xlsx 还是 csv,但会有失准时候,请自行指定。
Stream 类别无法判断来源于哪种 excel 请自行指定
- stream.SaveAs(excelType:ExcelType.CSV);
- //or
- stream.SaveAs(excelType:ExcelType.XLSX);
- //or
- stream.Query(excelType:ExcelType.CSV);
- //or
- stream.Query(excelType:ExcelType.XLSX);