MiniExcel簡介 簡單、高效避免OOM的.NET處理Excel查、寫、填充數據工具。 目前主流框架大多需要將數據全載入到記憶體方便操作,但這會導致記憶體消耗問題,MiniExcel 嘗試以 Stream 角度寫底層演算法邏輯,能讓原本1000多MB占用降低到幾MB,避免記憶體不夠情況。 特點: 低記憶體 ...
MiniExcel簡介
簡單、高效避免OOM的.NET處理Excel查、寫、填充數據工具。
目前主流框架大多需要將數據全載入到記憶體方便操作,但這會導致記憶體消耗問題,MiniExcel 嘗試以 Stream 角度寫底層演算法邏輯,能讓原本1000多MB占用降低到幾MB,避免記憶體不夠情況。
特點:
- 低記憶體耗用,避免OOM、頻繁 Full GC 情況
- 支持
即時
操作每行數據 - 兼具搭配 LINQ 延遲查詢特性,能辦到低消耗、快速分頁等複雜查詢
- 輕量,不需要安裝 Microsoft Office、COM+,DLL小於150KB
- 簡便操作的 API 風格
安裝 MiniExcel
導出數據
public class Student
{
public string? Name { get; set; }
public string? Home { get; set; }
public int? Age { get; set; }
}
//獲得當前目錄的路徑
string currentDirectory = Directory.GetCurrentDirectory();
//合併當前目錄與Excel文件名
var path = Path.Combine(currentDirectory, $"{Guid.NewGuid()}.xlsx");
List<Student> studentList = new List<Student>()
{
new Student { Name = "小東", Home = "New York", Age = 25 },
new Student { Name = "小西", Home = "London", Age = 22 },
new Student { Name = "小南", Home = "Paris", Age = 28 },
new Student { Name = "小北", Home = "Tokyo", Age = 24 },
new Student { Name = "小王", Home = "Berlin", Age = 26 }
};
MiniExcel.SaveAs(path, studentList);
導入Excel中如下圖所示:
但是目前還不支持Excel的插入:
因此如果遇到不僅僅只是生成Excel,後續還要向Excel添加數據的需求,可以用csv代替:
//獲得當前目錄的路徑
string currentDirectory = Directory.GetCurrentDirectory();
//合併當前目錄與CSV文件名
var path = Path.Combine(currentDirectory, $"{Guid.NewGuid()}.csv");
List<Student> studentList = new List<Student>()
{
new Student { Name = "小東", Home = "New York", Age = 25 },
new Student { Name = "小西", Home = "London", Age = 22 },
new Student { Name = "小南", Home = "Paris", Age = 28 },
new Student { Name = "小北", Home = "Tokyo", Age = 24 },
new Student { Name = "小王", Home = "Berlin", Age = 26 }
};
MiniExcel.SaveAs(path, studentList);
生成的CSV文件如下圖所示:
向CSV文件繼續添加數據:
//獲得當前目錄的路徑
string currentDirectory = Directory.GetCurrentDirectory();
//合併當前目錄與Excel文件名
//var path = Path.Combine(currentDirectory, $"{Guid.NewGuid()}.csv");
var path = Path.Combine(currentDirectory, "10de09bb-ad8c-4430-b717-5f24117a11a6.csv");
List<Student> studentList = new List<Student>()
{
new Student { Name = "小東", Home = "New York", Age = 25 },
new Student { Name = "小西", Home = "London", Age = 22 },
new Student { Name = "小南", Home = "Paris", Age = 28 },
new Student { Name = "小北", Home = "Tokyo", Age = 24 },
new Student { Name = "小王", Home = "Berlin", Age = 26 }
};
//MiniExcel.SaveAs(path, studentList);
MiniExcel.Insert(path, studentList);
繼續添加數據後的CSV文件如下圖所示:
導入數據
var path = "你的文件路徑";
var rows = MiniExcel.Query<Student>(path);
實現效果如下所示: