NPOI读取excel。excel 导入。日期类型读取
电脑版发表于:2019/1/25 23:18
NPOI是一个优秀的操作excel的库,可以很方便的进行excel的读取与导出
NPOI读取excel
public ActionResult ReadExcel() { //打开excel所在的位置 FileStream stream = new FileStream(Server.MapPath("~/excel/students.xls"), FileMode.Open); //获取excel HSSFWorkbook workbook = new HSSFWorkbook(stream); //获取excel中的表 HSSFSheet sheet = workbook.GetSheet("Sheet1") as HSSFSheet; //获取行 HSSFRow row = sheet.GetRow(0) as HSSFRow; //获取列 HSSFCell cell = row.GetCell(0) as HSSFCell; string str = cell.StringCellValue; //遍历行 for (int i = 0; i < sheet.LastRowNum; i++) { HSSFRow itemrow = sheet.GetRow(i) as HSSFRow; string value = itemrow.GetCell(0).StringCellValue; Response.Write(value + "<br/>"); } return View(); }
封装一个方法根据字符串的方式来读取单元格的值
因为类型多了,读取很容易报错
/// <summary> /// 根据string类型来获取单元格的值 /// </summary> /// <param name="hSSFCell"></param> /// <returns></returns> private string GetStringCellValue(NPOI.SS.UserModel.ICell hSSFCell) { if (hSSFCell == null) { return ""; } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Numeric) { // //NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型 if (NPOI.SS.UserModel.DateUtil.IsCellDateFormatted(hSSFCell)) { try { string dateTime = hSSFCell.DateCellValue.ToString(); return dateTime; } catch { /* * 很奇怪读取时不时会报错。 * 如果报错就使用数字类型读取然后使用GetJavaDate把数字转化成日期 */ DateTime dateTime = NPOI.SS.UserModel.DateUtil.GetJavaDate(hSSFCell.NumericCellValue); } } return hSSFCell.NumericCellValue.ToString(); } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.String) { return hSSFCell.StringCellValue; } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Boolean) { return hSSFCell.BooleanCellValue.ToString(); } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Blank) { return ""; } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Error) { return hSSFCell.ErrorCellValue.ToString(); } return ""; }
也可以按照泛型的类型来封装
注意通过这种方式,类型要能转化成功才行,不然会报类型转化的错误的
/// <summary> /// 根据传递过来的泛型来获取对应的类型数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="hSSFCell"></param> /// <returns></returns> private T GetCellValue<T>(NPOI.SS.UserModel.ICell hSSFCell) { Type t = typeof(T); if (hSSFCell == null) { return default(T); } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Numeric) { // //NPOI中数字和日期都是NUMERIC类型的,这里对其进行判断是否是日期类型 if (NPOI.SS.UserModel.DateUtil.IsCellDateFormatted(hSSFCell)) { return (T)(object)hSSFCell.DateCellValue; } return (T)(object)hSSFCell.NumericCellValue; } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.String) { return (T)(object)hSSFCell.StringCellValue; } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Boolean) { return (T)(object)hSSFCell.BooleanCellValue; } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Blank) { return default(T); } if (hSSFCell.CellType == NPOI.SS.UserModel.CellType.Error) { return (T)(object)hSSFCell.ErrorCellValue; } return default(T); }