使用POI读取Excel日期转LocalDateTime遇解析异常求助
Excel日期转LocalDateTime解析错误解决方法
问题场景
使用POI读取Excel日期,尝试通过LocalDateTime.parse二次解析时抛出错误:
java.time.format.DateTimeParseException: Text '2023-01-22T00:00' could not be parsed at index 2
Excel显示的日期格式为1/22/2023 12:00:00 AM,原代码如下:
DateTimeFormatter format=DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss"); LocalDateTime dateObj=LocalDateTime.parse(row.getCell(2).getLocalDateTimeCellValue().toString(),format); dto.setDate(dateObj);
错误原因
row.getCell(2).getLocalDateTimeCellValue()已经直接返回LocalDateTime对象,将其转为String后得到的是ISO标准格式(如2023-01-22T00:00),和你指定的MM/dd/yyyy hh:mm:ss格式不匹配,导致解析失败。
解决方案
方案1:直接使用POI返回的LocalDateTime对象
无需二次解析,直接赋值:
LocalDateTime dateObj = row.getCell(2).getLocalDateTimeCellValue(); dto.setDate(dateObj);
方案2:兼容多种单元格类型(日期存为文本/数字时)
如果Excel中日期可能以字符串或数字格式存储,需先判断单元格类型再处理:
Cell cell = row.getCell(2); LocalDateTime dateObj; if (cell.getCellType() == CellType.LOCAL_DATE_TIME) { dateObj = cell.getLocalDateTimeCellValue(); } else if (cell.getCellType() == CellType.STRING) { // 匹配Excel显示的"1/22/2023 12:00:00 AM"格式,Locale.US确保识别AM/PM DateTimeFormatter format = DateTimeFormatter.ofPattern("M/d/yyyy hh:mm:ss a", Locale.US); dateObj = LocalDateTime.parse(cell.getStringCellValue(), format); } else if (cell.getCellType() == CellType.NUMERIC) { // 处理POI中以数字存储的日期 dateObj = LocalDateTime.ofInstant( cell.getDateCellValue().toInstant(), ZoneId.systemDefault() ); } else { // 根据业务需求处理其他类型,比如抛出异常或设为null throw new IllegalArgumentException("不支持的单元格类型"); } dto.setDate(dateObj);
内容的提问来源于stack exchange,提问作者Tathagata Dasgupta
相关产品推荐
相关产品推荐

