1. 程式人生 > >C# WPF 利用NPOI讀寫Excel檔案。

C# WPF 利用NPOI讀寫Excel檔案。

關於C#讀寫Excel檔案的方法,在網上查來查去大致有三種

    1.利用Microsoft.Office.Interop.Excel提供的API進行讀寫,由於相容性比較差等原因,本人搞了半天之後放棄了。
    2.利用OpenXML庫進行讀寫,由於感覺很麻煩,本人看著教程看著看著就放棄了。。。
    3.利用NPOI開源庫進行讀寫,由於其不需要額外安裝別的東西(Office元件都可以不用),讓人感動,所以本人經過1s的思考後就決定用它了。

第一步,下載NPOI開源庫。地址,下載完成得到“NPOI 2.2.1 binary package.zip”(這個是當前最新的),如果你看到的時候不是這個,就下你能下的最新的。

第三步,在工程中引用“NPOI.dll”、“NPOI.OOXML.dll”和“NPOI.OpenXml4Net.dll”三個動態連結庫。

第四步,引用名稱空間

using NPOI.SS.UserModel;  
using NPOI.XSSF.UserModel;  
using NPOI.HSSF.UserModel;  

第五步,到此可以直接用NPOI的函式讀寫檔案了,有個好心人寫了個ExcelHelper類可以用,本人下來稍微修改了下,就直接用起來了,本來想貼那個人的部落格連結,結果發現忘記了。。反正這裡知道這個類的程式碼大體不是本人寫的就是了。

public class
ExcelHelper : IDisposable { private string fileName = null; //檔名 private IWorkbook workbook = null; private FileStream fs = null; private bool disposed; public ExcelHelper(string fileName)//建構函式,讀入檔名 { this.fileName = fileName; disposed = false; } /// 將excel中的資料匯入到DataTable中
/// <param name="sheetName">excel工作薄sheet的名稱</param> /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param> /// <returns>返回的DataTable</returns> public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn) { ISheet sheet = null; DataTable data = new DataTable(); int startRow = 0; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); workbook = WorkbookFactory.Create(fs); if (sheetName != null) { sheet = workbook.GetSheet(sheetName); //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet if (sheet == null) { sheet = workbook.GetSheetAt(0); } } else { sheet = workbook.GetSheetAt(0); } if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //一行最後一個cell的編號,即總的列數 if (isFirstRowColumn) { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (cellValue != null) { DataColumn column = new DataColumn(cellValue); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1;//得到項標題後 } else { startRow = sheet.FirstRowNum; } //最後一列的標號 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; //沒有資料的行預設是null        DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //同理,沒有資料的單元格都預設是null dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } return data; } catch (Exception ex)//列印錯誤資訊 { MessageBox.Show("Exception: " + ex.Message); return null; } } //將DataTable資料匯入到excel中 //<param name="data">要匯入的資料</param> //<param name="sheetName">要匯入的excel的sheet的名稱</param> //<param name="isColumnWritten">DataTable的列名是否要匯入</param> //<returns>匯入資料行數(包含列名那一行)</returns> public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (isColumnWritten == true) //寫入DataTable的列名 { IRow row = sheet.CreateRow(0); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName); } count = 1; } else { count = 0; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); } ++count; } workbook.Write(fs); //寫入到excel return count; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return -1; } } public void Dispose()//IDisposable為垃圾回收相關的東西,用來顯式釋放非託管資源,這部分目前還不是非常瞭解 { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (fs != null) fs.Close(); } fs = null; disposed = true; } } }

第六步,直接呼叫上面的ExcelHelper讀寫Excel檔案即可
讀Excel資料

using (ExcelHelper excelHelper = new ExcelHelper(@"I:\人員資訊表.xlsx"))  
{  
    dt = excelHelper.ExcelToDataTable("MySheet", true);//讀取資料  
    foreach (DataRow dr in dt.Rows)//DataTable轉ObservableCollection  
    {  
        personalInfoList.Add(new personalInfo(dr[0].ToString(), Int32.Parse(dr[1].ToString()), dr[2].ToString(), dr[3].ToString()));  
    }  
}  

寫Excel資料

using (ExcelHelper excelHelper = new ExcelHelper(@"I:\寫入人員資訊表.xlsx"))//定義一個範圍,在範圍結束時處理物件  
{  
    excelHelper.DataTableToExcel(dt, "MySheet", true);  
}