java 关于读取excel表内的日期时间

时间:2022-10-19 16:22:46

最近任务上遇到了需要读取excel表里的日期时间,在没有添加红色框框里的代码时,读到的值为一串数字。

后来搜索了资料并添加了这段代码后,就正确解析并读取到日期信息了。


/**
* 普通类型值设置
*
* @param rows
* @param obj
* @param cellConfig
* @throws Exception
* @throws CoreException
*/
private static void setNormalVal(List<Row> rows, Object obj, CellConfig cellConfig)
throws Exception, CoreException {
Cell cell = rows.get(0).getCell(cellConfig.getIndex());
String val = "";
if(cell != null){
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
val = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN:
Boolean val1 = cell.getBooleanCellValue();
val = val1.toString();
break;
case Cell.CELL_TYPE_NUMERIC:
//Double val3 = cell.getNumericCellValue();
//val = val3.toString();
if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
Date theDate = cell.getDateCellValue();
SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
val = dff.format(theDate);
}else{
DecimalFormat df = new DecimalFormat("0");
val = df.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BLANK:
break;
default:
throw new CoreException("数据类型配置不正确");
}
}
ReflectUtil.setObjField(obj, cellConfig.getValName(), String.class, val);
}