C#使用MiniExcel實現(xiàn)導(dǎo)入導(dǎo)出數(shù)據(jù)到Excel/CSV文件
MiniExcel簡介
簡單、高效避免OOM的.NET處理Excel查、寫、填充數(shù)據(jù)工具。
目前主流框架大多需要將數(shù)據(jù)全載入到內(nèi)存方便操作,但這會導(dǎo)致內(nèi)存消耗問題,MiniExcel 嘗試以 Stream 角度寫底層算法邏輯,能讓原本1000多MB占用降低到幾MB,避免內(nèi)存不夠情況。
特點(diǎn):
- 低內(nèi)存耗用,避免OOM、頻繁 Full GC 情況
- 支持
即時
操作每行數(shù)據(jù) - 兼具搭配 LINQ 延遲查詢特性,能辦到低消耗、快速分頁等復(fù)雜查詢
- 輕量,不需要安裝 Microsoft Office、COM+,DLL小于150KB
- 簡便操作的 API 風(fēng)格
安裝 MiniExcel
導(dǎo)出數(shù)據(jù)
public class Student { public string? Name { get; set; } public string? Home { get; set; } public int? Age { get; set; } } ? //獲得當(dāng)前目錄的路徑 string currentDirectory = Directory.GetCurrentDirectory(); ? //合并當(dāng)前目錄與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);
導(dǎo)入Excel中如下圖所示:
但是目前還不支持Excel的插入:
因此如果遇到不僅僅只是生成Excel,后續(xù)還要向Excel添加數(shù)據(jù)的需求,可以用csv代替:
//獲得當(dāng)前目錄的路徑 string currentDirectory = Directory.GetCurrentDirectory(); ? //合并當(dāng)前目錄與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文件繼續(xù)添加數(shù)據(jù):
//獲得當(dāng)前目錄的路徑 string currentDirectory = Directory.GetCurrentDirectory(); ? //合并當(dāng)前目錄與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);
繼續(xù)添加數(shù)據(jù)后的CSV文件如下圖所示:
導(dǎo)入數(shù)據(jù)
var path = "你的文件路徑"; var rows = MiniExcel.Query<Student>(path);
實現(xiàn)效果如下所示:
以上就是C#使用MiniExcel實現(xiàn)導(dǎo)入導(dǎo)出數(shù)據(jù)到Excel/CSV文件的詳細(xì)內(nèi)容,更多關(guān)于C# MiniExcel導(dǎo)入導(dǎo)出數(shù)據(jù)的資料請關(guān)注腳本之家其它相關(guān)文章!