问题:
我需要将一个excel文件的数据导入到列与之对应的mysql表中,但excel的时间格式在使用HSSFWorkbook读出来后格式很奇怪,如图。
excel的数据:
Workbook获取单元格cell的结果:
excel里明明写的是“2023/5/11 8:45”,但cell的结果却是 “11-五月-2023”这种奇葩格式。而我想要的是LocalDateTime的格式“yyyy-mm-dd hh:mm:ss”
所以这时候,我们可以使用Cell自带的方法来获取当前单元格的日期:
Date dateCellValue = cell.getDateCellValue();
得到Date格式,想转成LocalDateTime就很简单了:
LocalDateTime localDateTime = dateCellValue.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
我的代码:
/**
* @param :
* @return void
* @author pangshicheng
* @description 检查列类型格式
* @date 2023/5/11 9:03
*/
public static String checkColumnType(Cell cell,String type) throws Exception {
String result = cell.toString();
if("datetime".equals(type)){
try {
Date dateCellValue = cell.getDateCellValue();
LocalDateTime localDateTime = dateCellValue.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
}catch (Exception e){
throw new Exception("时间格式出错!请检查" + result +"的内容格式!");
}
}else if("geometry".equals(type)){
result ="";
}
return result;
}