public static DataTable ReadExcelToDataTable(string fileName, string sheetName = null, bool isFirstRowColumn = false) { //定義要返回的datatable對象 DataTable ...
public static DataTable ReadExcelToDataTable(string fileName, string sheetName = null, bool isFirstRowColumn = false) { //定義要返回的datatable對象 DataTable data = new DataTable(); NPOI.SS.UserModel.ISheet sheet = null; //數據開始行(排除標題行) int startRow = 0; if (!File.Exists(fileName)) { return null; } //根據指定路徑讀取文件 FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); NPOI.SS.UserModel.IWorkbook workbook = NPOI.SS.UserModel.WorkbookFactory.Create(fs); //IWorkbook workbook = new HSSFWorkbook(fs); //如果有指定工作表名稱 if (!string.IsNullOrEmpty(sheetName)) { sheet = workbook.GetSheet(sheetName); //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet if (sheet == null) { sheet = workbook.GetSheetAt(0); } } else { //如果沒有指定的sheetName,則嘗試獲取第一個sheet sheet = workbook.GetSheetAt(0); } if (sheet != null) { NPOI.SS.UserModel.IRow firstRow = sheet.GetRow(0); //一行最後一個cell的編號 即總的列數 int cellCount = firstRow.LastCellNum; //如果第一行是標題列名 for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { NPOI.SS.UserModel.ICell cell = firstRow.GetCell(i); if (cell != null) //遍歷Excel表 { // string cellValue = cell.StringCellValue; if (cell != null) { DataColumn column = new DataColumn(cell.ToString()); data.Columns.Add(column); } } } if (isFirstRowColumn) { startRow = sheet.FirstRowNum + 1; //有表頭時不讀取表頭 } else { startRow = sheet.FirstRowNum; } //最後一列的標號 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i) { NPOI.SS.UserModel.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; }
非原創