NPOI組件強大高效,這裡只使用它完成我們的Excel寫入功能,需要更多內容則請自行搜索。
先處理翻頁問題,10版Excel最多支持1048576行,03版Excel最多支持65536行。只處理03版Excel,除去表頭,翻頁算法如下:
IWorkbook workbook = = Int32 RowPerSheet = (Int32 r = ; r < records.Count; r++ ((r % RowPerSheet) == = (Int32)((Double)r / RowPerSheet) + = workbook.CreateSheet( + (Int32 i = ; i < headers.Count; i++ IRow row = sheet.CreateRow(r % RowPerSheet + (Int32 i = ; i < props.Length; i++
注意引用NPOI.SS.UserModel和NPOI.HSSF.UserModel命名空間,現在我們有Row,那麼創建單元格寫入內容就容易了。
考慮到導出一個65536行的工作表,看的人會抓狂,於是封裝導出方法到ExcelHelper類,提供行數屬性及導出方法,同時將Header類設置為其內部類(這個不是必須的,但重命名一下可能沒錯),實現如下:
String Name { ; String PrintName { ; == Int32 MaxRowPerSheet = Int32 rowPerSheet = { (value < || value > ArgumentOutOfRangeException(= IWorkbook Export<T>(IList<T> (records == ArgumentNullException(= (T).GetProperties().Select(p => Export<T> IWorkbook Export<T>(IList<T> records, IList<String> (records == ArgumentNullException( (headers == || headers.Count == ArgumentNullException(= (T).GetProperties().Select(p => Export<T> IWorkbook Export<T>(IList<T> records, IList<Header> (records == ArgumentNullException( (headers == || headers.Count == ArgumentNullException(= ( i = ; i < headers.Count; i++= (T).GetProperty(headers[i].Name); = = = ( r = ; r < records.Count; r++ ((r % RowPerSheet) == = (Int32)((Double)r / RowPerSheet) + = workbook.CreateSheet( += sheet.CreateRow( ( i = ; i < headers.Count; i++ row = sheet.CreateRow(r % RowPerSheet + ( i = ; i < props.Length; i++ (props[i] != ) = props[i].GetValue(records[r], (value != (Int32 i = ; i < workbook.NumberOfSheets; i++= (Int32 h = ; h < headers.Count; h++
客戶端調用如下:
Main(<Person> persons = List<Person> = (Int32 i = ; i < records; i++ Person { ID = i, Name = + i, Birth = DateTime(, , ), Salary = <ExcelHelper.Header> headers = List<ExcelHelper.Header> ExcelHelper.Header( ExcelHelper.Header(, ExcelHelper.Header(, ExcelHelper.Header(, = = = excelHelper.Export<Person>= (FileStream stream =
至此功能已完成,但細節待完善,觀察“生日”列所有值都是1980-10-01 00:00:00,這是單元格值設置語句row.CreateCell(i).SetCellValue(value.ToString())過於簡單的緣故,後續一篇繼續,讀者也可以參考NPOI組件的ICell屬性與方法自行完成。