最近沒什么時間,主線劇情是玩不來了,所以偷個懶,打一個直線任務(wù)。 如果我們的程序?qū)Σ僮鱁xcel有需求,那么NPOI應(yīng)該不會陌生。不過這里并不打算說NPOI,而是另外一個使用簡單的工具:MiniExcel https://gitee.com/dotnetchina/MiniExcel MiniExcel簡單、高效避免OOM的.NET處理Excel查、寫、填充數(shù)據(jù)工具。 目前主流框架大多需要將數(shù)據(jù)全載入到內(nèi)存方便操作,但這會導(dǎo)致內(nèi)存消耗問題,MiniExcel 嘗試以 Stream 角度寫底層算法邏輯,能讓原本1000多MB占用降低到幾MB,避免內(nèi)存不夠情況。 特點
上面是關(guān)于MiniExcel的簡單介紹,下面開始實戰(zhàn)。 我這里新建一個WPF項目,添加一個DataGrid用于顯示數(shù)據(jù)。 綁定Students數(shù)據(jù),
StudentInfo類屬性如下, public class StudentInfo { public string Name { get; set; } public string Age { get; set; } public string Grade { get; set; } } 新建一個xlsx表格,數(shù)據(jù)如下,title與StudentInfo對應(yīng) 通過Nuget加載MiniExcel。 當(dāng)我們需要讀取數(shù)據(jù),使用Query方法;
我們可以看到,MiniExcel使用的是靜態(tài)方法,返回的數(shù)據(jù)是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; } } 當(dāng)我們轉(zhuǎn)換為List,就可以進行更多的處理。 將數(shù)據(jù)寫入Excel,使用SaveAS方法。
注意我們這里的overwriteFile:true 如果不設(shè)定覆蓋文件,那么當(dāng)student.xlsx存在,那么就引發(fā)IO異常 |
|
來自: 新用戶0118F7lQ > 《文件夾1》