1. 程式人生 > >NPOI操作Excel

NPOI操作Excel

count dex obj ble 基礎 支持 taf ssa .com

一、引言

昨天公司EDI導入功能出現問題,經排查是由於引用Com組件Microsoft.Office.Interop.Excel.dll,操作Excel引起,可是現在客戶電腦壓根都沒裝Office,還倒個鬼數據啊(畫個圈圈xx下之前寫這個功能的人),一次重構操作Excel功能之旅由此開始。。。

二、NPOI操作Excel

1.整個Excel(工作薄):WorkBook,包含的頁(工作表):Sheet, 行:Row, 單元格:Cell。

2.HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,擴展名是.xls ;

XSSFWorkbook:是操作Excel2007及以上的版本,擴展名是.xlsx。

3.NPOI組件下載地址:https://npoi.codeplex.com/

4.如果是.NET Framwork環境,請將下載的npoi組件都引用一下,如果是.NET Core環境,就在NuGet程序包中搜索安裝 DotNetCore.NPOI 這個程序包即可

5.NPOI源碼地址:https://github.com/tonyqus/npoi

下面是NPOI讀寫Excel的例子,ExcelHelper是自己封裝的類庫,包括創建Excel,Excel寫入txt,Excel寫入DataTable,DataTable寫入Excel等

技術分享
using System;
using System.Collections.Generic;
using System.Linq; using System.Text; using NPOI.HSSF.UserModel;//HSSFWorkbook using NPOI.SS.UserModel;//ISheet using System.IO; using NPOI.XSSF.UserModel; using System.Data; namespace NetUtilityLib { public class ExcelHelper { /// <summary> /// 基礎demo 創建默認版本的excel /// </summary>
/// <param name="path">需要創建的excel路徑</param> private static void CreateExcel(string path) { try { #region //操作excel 03版本 //創建工作薄 HSSFWorkbook hssfworkbook = new HSSFWorkbook(); hssfworkbook.CreateSheet("Sheet1"); hssfworkbook.CreateSheet("Sheet2"); hssfworkbook.CreateSheet("Sheet3"); //根據名稱獲取指定Sheet頁 ISheet sheet = hssfworkbook.GetSheet("Sheet1"); //根據索引 創建所在行 row range 0~65535 IRow row = sheet.CreateRow(1); for (int i = 0; i < 20; i++) { ICell cell = row.CreateCell(i);//在行中創建單元格 cell.SetCellValue(i);//向單元格張添加數據 } //打開excel文件,不存在就創建excel using (FileStream file = new FileStream(@"F:/test.xls", FileMode.OpenOrCreate, FileAccess.ReadWrite)) { //將工作薄hssfworkbook 寫入excel hssfworkbook.Write(file); } #endregion } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); throw new Exception(ex.Message); } } /// <summary> /// 創建工作薄 /// </summary> /// <param name="path">excel路徑</param> /// <param name="workbook">創建的工作薄</param> /// <returns>創建工作薄是否成功</returns> private static bool GetWorkbook(string path, out IWorkbook workbook) { if (path.IndexOf("xlsx") > 0) { workbook = new XSSFWorkbook();//07 及以上 } else if (path.IndexOf("xls") > 0) { workbook = new HSSFWorkbook();//03 } else { workbook = null; return false; } return true; } /// <summary> /// 讀取時 創建工作薄 /// </summary> /// <param name="path">excel的路徑</param> /// <param name="workbook">將數據讀進工作薄</param> /// <param name="fs">數據流</param> /// <returns>數據是否能夠讀進excel中</returns> private static bool GetWorkbook(string path, out IWorkbook workbook, FileStream fs) { if (path.IndexOf("xlsx") > 0) { workbook = new XSSFWorkbook(fs);//07 及以上 } else if (path.IndexOf("xls") > 0) { workbook = new HSSFWorkbook(fs);//03 } else { workbook = null; return false; } return true; } /// <summary> /// 創建一個excel /// </summary> /// <param name="path">要創建的excel路徑及名稱</param> /// <param name="sheetNames">要創建的excel的sheet頁名稱集合</param> /// <returns>創建是否成功</returns> public static bool CreateExcel(string path, IList<string> sheetNames) { try { IWorkbook workbook = null; FileStream fs = null; if (!GetWorkbook(path, out workbook)) { return false; } if (sheetNames.Count > 0) { foreach (string sheetName in sheetNames) { workbook.CreateSheet(sheetName); } } else { workbook.CreateSheet("Sheet1"); workbook.CreateSheet("Sheet2"); workbook.CreateSheet("Sheet3"); } using (fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { workbook.Write(fs); } return true; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); throw new Exception(ex.Message); } } /// <summary> /// 將excel中數據導入到txt中 /// </summary> /// <param name="excelPath">要導出的excel路徑及名稱</param> /// <param name="txtPath">要導入的txtl路徑及名稱</param> /// <returns>是否導入txt成功</returns> public static bool ExcelToTxt(string excelPath, string txtPath) { try { IWorkbook workbook = null; FileStream fs = null; object cellValue = DBNull.Value; StringBuilder sbr = new StringBuilder(); using (fs = new FileStream(excelPath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { if (!GetWorkbook(excelPath, out workbook, fs)) { return false; } for (int i = 0; i < workbook.NumberOfSheets; i++) //NumberOfSheets是excel中總共的表數 { ISheet sheet = workbook.GetSheetAt(i); //讀取當前表數據 for (int j = 0; j <= sheet.LastRowNum; j++) //LastRowNum 是當前表的總行數 { IRow row = sheet.GetRow(j); //讀取當前行數據 if (row != null) { sbr.Append("\r\n");//換行 for (int k = 0; k <= row.LastCellNum; k++) //LastCellNum 是當前行的總列數 { ICell cell = row.GetCell(k); //當前表格 if (cell != null) { cellValue = GetCellValue(cell); } sbr.Append(cellValue + "\t"); //獲取表格中的數據 cellValue = DBNull.Value; } } } } } sbr.ToString(); using (StreamWriter wr = new StreamWriter(new FileStream(txtPath, FileMode.Append))) //把讀取excel文件的數據寫入txt文件中 { wr.Write(sbr.ToString()); wr.Flush(); } return true; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); throw new Exception(ex.Message); } } /// <summary> /// 將excel中的數據導入到DataTable中 /// </summary> /// <param name="data">要導入的excel路徑及名稱</param> /// <param name="sheetName">excel工作薄sheet的名稱</param> /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param> /// <returns>返回的DataTable</returns> public static DataTable ExcelToDataTable(string excelPath, string sheetName, bool isFirstRowColumn) { IWorkbook workbook = null; ISheet sheet = null; FileStream fs = null; object cellValue = DBNull.Value; DataTable data = new DataTable(); int startRow = 0; try { using (fs = new FileStream(excelPath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { if (!GetWorkbook(excelPath, out workbook, fs)) { return null; } if (sheetName != null) { sheet = workbook.GetSheet(sheetName); if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet { 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) { cellValue = GetCellValue(cell); if (cellValue != null) { DataColumn column = new DataColumn(cellValue.ToString()); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1; } else { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { DataColumn column = new DataColumn(); data.Columns.Add(column); } 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) { dataRow[j] = row.GetCell(j) == null ? DBNull.Value : GetCellValue(row.GetCell(j)); } data.Rows.Add(dataRow); } } } return data; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message); return null; } } /// <summary> /// 將DataTable數據導入到excel中 /// </summary> /// <param name="data">要導入的excel路徑及名稱</param> /// <param name="data">要導入的數據</param> /// <param name="isColumnWritten">DataTable的列名是否要導入</param> /// <param name="sheetName">要導入的excel的sheet的名稱</param> /// <returns>導入數據行數(包含列名那一行)</returns> public static int DataTableToExcel(string excelPath, DataTable data, string sheetName, bool isColumnWritten) { int i = 0; int j = 0; int count = 0; IWorkbook workbook = null; ISheet sheet = null; FileStream fs = null; try { using (fs = new FileStream(excelPath, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { if (!GetWorkbook(excelPath, out workbook)) { return -1; } sheetName = sheetName != "" ? sheetName : "Sheet1"; sheet = workbook.CreateSheet(sheetName); 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) { System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message); return -1; } } /// <summary> /// 獲取excel中單元格的數據 /// </summary> /// <param name="pCell">獲取到的單元格</param> /// <returns>單元格中數據</returns> private static object GetCellValue(ICell pCell) { object objReturn; try { switch (pCell.CellType) { case CellType.Blank: objReturn = DBNull.Value; break; //case CellType.Boolean: // break; //case CellType.Error: // break; case CellType.Formula: objReturn = TryReturn(pCell); break; case CellType.Numeric: if (pCell.CellStyle.DataFormat == 14 || pCell.CellStyle.DataFormat == 22 || pCell.CellStyle.DataFormat == 165 || pCell.CellStyle.DataFormat == 164 || pCell.CellStyle.DataFormat == 191 || pCell.CellStyle.DataFormat == 195)//14為日期類型 { //來自Excel單元格的數據如果能轉為日期類型,則取DateCellValue 不可以則NumericCellValue DateTime dtCellValue; if (DateTime.TryParse(pCell.ToString(), out dtCellValue)) { if (pCell.ToString().IndexOf(",") > -1) objReturn = pCell.NumericCellValue; else objReturn = pCell.DateCellValue; } else { objReturn = pCell.NumericCellValue; } } else { objReturn = pCell.NumericCellValue; } break; case CellType.String: objReturn = pCell.StringCellValue; break; //case CellType.Unknown: // break; default: objReturn = pCell.ToString(); break; } return objReturn; } catch (Exception) { objReturn = pCell.ToString(); } return objReturn; } /// <summary> /// 用於容錯,當NumericCellValue出現異常時,默認取StringCellValue的值. /// </summary> /// <param name="pCell"></param> /// <returns></returns> private static object TryReturn(ICell pCell) { object objReturn; try { objReturn = pCell.NumericCellValue; return objReturn; } catch { objReturn = pCell.StringCellValue; return objReturn; } } } }
View Code

源代碼已上傳至:https://github.com/jdzhang1221/NetUtilityLib

寫在後面:

如果你是大牛,請多多批評指正文中不足;

如果你和博主一樣是小白,請點下右下角推薦,因為你的支持是我堅持不懈的動力;

如感興趣請多提寶貴意見,大家互相學習,共同進步!

參考:

http://www.cnblogs.com/savorboard/p/dotnetcore-npoi.html

http://www.cnblogs.com/knowledgesea/archive/2012/11/16/2772547.html

http://www.cnblogs.com/luxiaoxun/p/3374992.html

https://github.com/tonyqus/npoi

NPOI操作Excel