C# 用NPOI儲存為Excel檔案
阿新 • • 發佈:2019-01-06
首先下載NPOI元件,版本:NPOI 2.0
下載後新增引用(這裡有.net2.0版和4.0版的,按需引用)
使用方法如下:
/// <summary> /// 儲存成excel(NPOI方式) /// </summary> private void SaveToExcel() { List<Object> listFieldValue = FieldValueList;// 任意一個list或者其他資料 // 使用NPOI匯出 NPOI.HSSF.UserModel.HSSFWorkbook stBook = new NPOI.HSSF.UserModel.HSSFWorkbook(); NPOI.SS.UserModel.ISheet stSheet = stBook.CreateSheet("引數計算表"); // 第一行(表頭) NPOI.SS.UserModel.IRow stRow1 = stSheet.CreateRow(0); stRow1.CreateCell(0).SetCellValue("欄位名"); stRow1.CreateCell(1).SetCellValue("引數值"); stRow1.CreateCell(2).SetCellValue("最小值"); stRow1.CreateCell(3).SetCellValue("最大值"); stRow1.CreateCell(4).SetCellValue("計算方法"); int iTotalCount = listFieldValue.Count; // 新增每一行資料 for (int i = 0; i < iTotalCount; i++) { NPOI.SS.UserModel.IRow stRowN = stSheet.CreateRow(i + 1); stRowN.CreateCell(0).SetCellValue(listFieldValue[i].Name); stRowN.CreateCell(1).SetCellValue(listFieldValue[i].Value); stRowN.CreateCell(2).SetCellValue(listFieldValue[i].Min); stRowN.CreateCell(3).SetCellValue(listFieldValue[i].Max); stRowN.CreateCell(4).SetCellValue(listFieldValue[i].Method); } // 自動列寬 for (int i = 0; i < 5; i++) { stSheet.AutoSizeColumn(i); } Microsoft.Win32.SaveFileDialog dlgSave = new Microsoft.Win32.SaveFileDialog(); // 預設檔名 dlgSave.FileName = "新建Excel表格"; // 預設副檔名 dlgSave.DefaultExt = ".xls"; // 預設過濾器 dlgSave.Filter = "Excel表格 (.xls)|*.xls"; // 顯示儲存對話方塊 Nullable<bool> bResult = dlgSave.ShowDialog(); if (bResult == true) { string strFileName = dlgSave.FileName; // 例項化一個檔案流 FileStream streamFile = new FileStream(strFileName, FileMode.Create);
// 獲得位元組陣列 System.IO.MemoryStream streamMemory = new System.IO.MemoryStream(); stBook.Write(streamMemory); byte[] data = streamMemory.ToArray(); // 開始寫入 streamFile.Write(data, 0, data.Length); // 清空緩衝區、關閉流 streamFile.Flush(); streamFile.Close(); stBook = null; streamMemory.Close(); streamMemory.Dispose(); } }