Java读取XLSX日期单元格报错:Text 'Time' could not be parsed at index 0
Java读取XLSX日期单元格格式化问题
我尝试在Java中读取XLSX表格的日期单元格,并将其格式化为MM/dd/yyyy格式,编写的代码如下:
Cell celldate=row.getCell(2); String value=formatter.formatCellValue(celldate); CellType type=celldate.getCellType(); String dat=value; if(dat!="") { DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a"); // Parsing the date LocalDateTime date = LocalDateTime.parse(dat,inputFormat); // Format for output DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy"); // Printing the date System.out.println(date.format(outputFormat));
运行时出现错误:Text 'Time' could not be parsed at index 0。
表格第2列为日期列,表头文本是"Time",数据行的内容示例为12-09-2023 10:08 am。
奇怪的是,当我手动将dat赋值为表格中的日期字符串"12-09-2023 10:08 am"时,代码可以正常运行,对应代码如下:
Cell cellname=row.getCell(7); String stname=cellname.getStringCellValue(); Cell celldate=row.getCell(2); String value=formatter.formatCellValue(celldate); CellType type=celldate.getCellType(); String dat="12-09-2023 10:08 am"; if(dat!="") { DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a"); // Parsing the date LocalDateTime date = LocalDateTime.parse(dat,inputFormat); // Format for output DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy"); // Printing the date System.out.println(date.format(outputFormat));
问题原因
错误提示直接说明代码读取到的是表头文本"Time",而非日期内容——这是因为你没有跳过表格的表头行,直接读取了索引为0的第一行(POI中行索引从0开始),拿到的是表头字符串,自然无法用日期格式解析。
解决方法
1. 跳过表头行
遍历工作表行时,从索引为1的行开始,只处理数据行,避开表头行。
2. 优化日期读取逻辑
POI对日期单元格有原生支持,无需先转字符串再解析,直接读取日期值更可靠;同时要处理单元格为空、类型不匹配的情况,避免异常。
修正后的完整代码示例
// 假设sheet是已获取的XSSFSheet/HSSFSheet对象 for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) { Row row = sheet.getRow(rowIndex); if (row == null) continue; // 跳过空行 Cell dateCell = row.getCell(2); if (dateCell == null) { System.out.println(""); continue; } String formattedDate = ""; // 判断是否为日期类型单元格 if (dateCell.getCellType() == CellType.NUMERIC && DateUtil.isCellDateFormatted(dateCell)) { Date date = dateCell.getDateCellValue(); SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); formattedDate = sdf.format(date); } else { // 处理字符串类型的日期(比如手动输入的日期文本) String dateStr = dateCell.getStringCellValue().trim(); if (!dateStr.isEmpty()) { DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a"); try { LocalDateTime date = LocalDateTime.parse(dateStr, inputFormatter); DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM/dd/yyyy"); formattedDate = date.format(outputFormatter); } catch (DateTimeParseException e) { // 解析失败时的容错处理 System.out.println("日期格式解析失败:" + dateStr); } } } System.out.println(formattedDate); }
额外注意点
- 不要用
!= ""判断字符串为空,改用!dateStr.isEmpty(),避免字符串前后空格导致的误判。 - 增加
try-catch捕获日期解析异常,避免单个单元格格式错误导致整个程序崩溃。 - 读取行和单元格时要判断是否为
null,防止空指针异常。
内容的提问来源于stack exchange,提问作者mm m
相关产品推荐
相关产品推荐

