public static class ExcelHelper { /// <summary> /// 獲取單元格的值 /// </summary> /// <param name="sheet">Excel sheet表名稱</param> /// <param name="rowIndex">行索引</param> /// <param name="cellIndex">列索引</param> /// <returns>行索引和列索引從0開始</returns> ///這個方法是用來檢查若是你不知道你的單元格里的值是什麼類型的就能夠用這個方法檢查 ///返回的字符串表明了單元格內容的值類型 public static string GetCellValue(this ISheet sheet, int rowIndex, int cellIndex) { string returnValue = string.Empty; //拼接的條件 if (sheet != null) { //若是當前的sheet不等於空 則獲取索引行的值 var row = sheet.GetRow(rowIndex); if (row != null) { //若是行內容不爲空 則獲取列 var cell = row.GetCell(cellIndex); if (cell != null) { //列也不爲空則判斷列中的值的類型 switch (cell.CellType) { //若是爲string類型,則返回String類型 case CellType.String: returnValue = cell.StringCellValue; break; //若是是數字類類型 case CellType.Numeric: //判斷是否爲日期類型 if (DateUtil.IsCellDateFormatted(cell)) { //是日期類型則轉化成日期輸出 returnValue = DateTime.FromOADate(cell.NumericCellValue).ToString(); } else { //輸出數字類型 returnValue = Convert.ToDouble(cell.NumericCellValue).ToString(); } break; //是不是bool類型 case CellType.Boolean: returnValue = Convert.ToString(cell.BooleanCellValue); break; //錯誤函數類型 case CellType.Error: returnValue = ErrorEval.GetText(cell.ErrorCellValue); break; case CellType.Formula: switch (cell.CachedFormulaResultType) { case CellType.String: string strFORMULA = cell.StringCellValue; if (strFORMULA != null && strFORMULA.Length > 0) { returnValue = strFORMULA.ToString(); } break; case CellType.Numeric: returnValue = Convert.ToString(cell.NumericCellValue); break; case CellType.Boolean: returnValue = Convert.ToString(cell.BooleanCellValue); break; case CellType.Error: returnValue = ErrorEval.GetText(cell.ErrorCellValue); break; default: break; } break; default: break; } } } } return returnValue.Trim(); } /// <summary> /// Excel導入 /// </summary> /// <typeparam name="T">這個方法是將Excle轉化成泛型導入</typeparam> /// <param name="columns">數組形式 列頭</param> /// <param name="excelStream">文件流</param> /// <param name="excelType">文件類型</param> /// <returns>這是Excel導入List泛型導入</returns> public static List<T> ReadExcel<T>(string[] columns, Stream excelStream, string excelType = ".xlsx") { //先創建一個泛型 var result = new List<T>(); int j=0, k=0; try { //建立一個空的文件薄 IWorkbook workbook = null; //若是文件類型爲xlsx //作這個判斷使檢測Excel的版本的 if (excelType == ".xlsx") { //空的文件博等於XSSFWorkbook讀取文件流 workbook = new XSSFWorkbook(excelStream); } else { //若是是.xls就是HSSFWorkbook讀取文件流 workbook = new HSSFWorkbook(excelStream); } //工做簿是否大於零?若是大於零獲取第一個工做薄的內容,不然空值 ISheet sheet = workbook.NumberOfSheets > 0 ? workbook.GetSheetAt(0) : null; if (sheet == null) { //工做薄若是爲空值 轉化失敗 return result; } //這裏定義的是反射類型 var type = typeof(T); //遍歷工做薄的內容 for (j = 1; j <= sheet.LastRowNum-1; j++)//第一行默認是表頭再去掉後面的說明的1行 { //動態建立動態類 var model = Activator.CreateInstance(type); //行的值來自於sheet獲取座標爲j的內容 由於第一行默認爲表頭,因此j從1開始 IRow row = sheet.GetRow(j); if (row != null) { //columns導入的Excel標題頭 for ( k = 0; k < columns.Length; k++) { //pro獲得的列頭的類型 var pro = type.GetProperty(columns[k]); if (pro != null) { //聲明一個弱類型 Object value; //列值獲取 ICell cell = row.GetCell(k); //處理獲取到的列值類型 switch (cell.CellType) { case CellType.Blank: //空數據類型處理 value = null; break; case CellType.String: //字符串類型 value = cell.StringCellValue; break; case CellType.Numeric: //數字類型 if (DateUtil.IsCellDateFormatted(cell))//日期類型 { value = cell.DateCellValue; } else//其餘數字類型 { value = cell.NumericCellValue; } break; case CellType.Formula: HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook); value = e.Evaluate(cell).StringValue; break; default: value = null; break; } if (value != null) { if (pro.GetType().Name == typeof(string).Name) { //插入值 pro.SetValue(model, Convert.ChangeType(value.ToString(), pro.PropertyType), null); } else pro.SetValue(model, Convert.ChangeType(value, pro.PropertyType), null); } } } //將獲得的值插入到T中(將T強制轉化爲Model類) result.Add((T)model); } } } catch (Exception ex) { throw new Exception("excel讀取失敗:第"+j+"行第"+k+"列數據錯誤:", ex); } return result; } /// <summary> /// 將sheet中的數據導出到datatable中 /// </summary> /// <param name="sheet">須要導出的sheet</param> /// <param name="HeaderRowIndex">表頭所在行號,-1表示沒有表頭</param> /// <returns>將Excel導出成Datatable</returns> private static DataTable ImportDt(ISheet sheet, int HeaderRowIndex, bool needHeader) { //新建立一個datatable DataTable table = new DataTable(); IRow headerRow; int cellCount; try { //表頭索引小於零時 輸出表頭 if (HeaderRowIndex < 0 || !needHeader) { //獲取行索引爲sheet表第一行 headerRow = sheet.GetRow(0); //獲取不爲空的列個數 cellCount = headerRow.LastCellNum; //獲取第一列的值 for (int i = headerRow.FirstCellNum; i <= cellCount; i++) { DataColumn column = new DataColumn(Convert.ToString(i)); table.Columns.Add(column); } } else { //獲取行內容 headerRow = sheet.GetRow(HeaderRowIndex); cellCount = headerRow.LastCellNum; //獲取第一行第一個單元格內容 for (int i = headerRow.FirstCellNum; i <= cellCount; i++) { if (headerRow.GetCell(i) == null) { if (table.Columns.IndexOf(Convert.ToString(i)) > 0) { DataColumn column = new DataColumn(Convert.ToString("重複列名" + i)); table.Columns.Add(column); } else { DataColumn column = new DataColumn(Convert.ToString(i)); table.Columns.Add(column); } } else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > 0) { DataColumn column = new DataColumn(Convert.ToString("重複列名" + i)); table.Columns.Add(column); } else { DataColumn column = new DataColumn(headerRow.GetCell(i).ToString()); table.Columns.Add(column); } } } int rowCount = sheet.LastRowNum; for (int i = (HeaderRowIndex + 1); i <= sheet.LastRowNum; i++) { try { IRow row; if (sheet.GetRow(i) == null) { row = sheet.CreateRow(i); } else { row = sheet.GetRow(i); } DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j <= cellCount; j++) { try { if (row.GetCell(j) != null) { switch (row.GetCell(j).CellType) { case CellType.String: string str = row.GetCell(j).StringCellValue; if (str != null && str.Length > 0) { dataRow[j] = str.ToString(); } else { dataRow[j] = null; } break; case CellType.Numeric: if (DateUtil.IsCellDateFormatted(row.GetCell(j))) { dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue); } else { dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue); } break; case CellType.Boolean: dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue); break; case CellType.Error: dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue); break; case CellType.Formula: switch (row.GetCell(j).CachedFormulaResultType) { case CellType.String: string strFORMULA = row.GetCell(j).StringCellValue; if (strFORMULA != null && strFORMULA.Length > 0) { dataRow[j] = strFORMULA.ToString(); } else { dataRow[j] = null; } break; case CellType.Numeric: dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue); break; case CellType.Boolean: dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue); break; case CellType.Error: dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue); break; default: dataRow[j] = ""; break; } break; default: dataRow[j] = ""; break; } } } catch (Exception exception) { throw new Exception(exception.Message); } } table.Rows.Add(dataRow); } catch (Exception exception) { throw new Exception(exception.Message); } } } catch (Exception exception) { throw new Exception(exception.Message); } return table; } }