/// <summary> /// 根据Excel列类型获取列的值 /// </summary> /// <param name="cell">Excel列</param> /// <returns></returns> public static string GetCellValue(ICell cell) { if (cell == null) { return string.Empty; } switch (cell.CellType) { case CellType.Blank: return string.Empty; case CellType.Boolean: return cell.BooleanCellValue.ToString(); case CellType.Error: return cell.ErrorCellValue.ToString(); case CellType.Numeric: short format = cell.CellStyle.DataFormat; if (format == 14 || format == 31 || format == 57 || format == 58) { //DateTime date = cell.DateCellValue;//这里报错,断点走进来不报错
DateTime date = DateTime.FromOADate(cell.NumericCellValue);//修改成这个 string re = date.ToString("yyy-MM-dd"); return re; } else { return cell.ToString(); } case CellType.Unknown: default: //This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number return cell.ToString(); case CellType.String: return cell.StringCellValue; case CellType.Formula: try { HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook); e.EvaluateInCell(cell); return cell.ToString(); } catch { return cell.NumericCellValue.ToString(); } } }
补充Execl获取导入的数据
//判定Execl版本 ISheet sheet = null; var inp = File.InputStream; if (POIFSFileSystem.HasPOIFSHeader(inp)) { var hssfworkbook = new HSSFWorkbook(inp); sheet = hssfworkbook.GetSheetAt(0); } if (POIXMLDocument.HasOOXMLHeader(inp)) { var hssfworkbook = new XSSFWorkbook(OPCPackage.Open(inp)); sheet = hssfworkbook.GetSheetAt(0); }
DataTable table = new DataTable(); IRow headerRow = sheet.GetRow(0);//第一行为标题行 int cellCount = headerRow.LastCellNum; int rowCount = sheet.LastRowNum; for (int i = headerRow.FirstCellNum; i < cellCount; i++) { DataColumn column = new DataColumn(ConvertNameToField(headerRow.GetCell(i).StringCellValue)); table.Columns.Add(column); } var check = CheckExcel(table); if (check != "") { return Json(new { result, message = check }, JsonRequestBehavior.AllowGet); } for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++) { IRow row = sheet.GetRow(i); DataRow dataRow = table.NewRow(); if (row != null) { for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) { dataRow[j] = GetCellValue(row.GetCell(j)); } } } table.Rows.Add(dataRow); }