XLSX自定义date格式读作String

我有这个date在单元格中的xlsx: 41883.0当我使用apache POI读取xlsx单元格时,它写道: 41883.0

这是我如何做到这一点:

 while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); cell.setCellType(Cell.CELL_TYPE_STRING); System.out.print(cell.getStringCellValue() + ";"); } 

由于我已经转换所有单元格成为stringtypes,我希望没有变形的date…

任何解决scheme 包含date的单元格的apache poi DataFormatter这是解决scheme:)

为什么? 为什么哦为什么哦为什么你会写这个代码开始呢? 这只是错误的这么多的层面上,大概每隔三分之一Stackoverflow的Apache POI问题覆盖:(哦,并明确build议不要在JavaDocs ….

你有两种select可供你使用。 如果要完全控制读取值,请按照Apache POI文档中关于读取单元格值的说明进行操作 ,并编写如下代码:

 for (Row row : sheet1) { for (Cell cell : row) { CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex()); System.out.print(cellRef.formatAsString()); System.out.print(" - "); switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.println(cell.getRichStringCellValue().getString()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { System.out.println(cell.getDateCellValue()); } else { System.out.println(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN: System.out.println(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: System.out.println(cell.getCellFormula()); break; default: System.out.println(); } } } 

另外,如果你只想“给我最接近的string,你可以在Excel中看到这个单元格”,那么你需要使用DataFormatter类 ,它提供了读取应用于单元格的Excel格式规则的方法,用Java创build(尽可能)

你的代码应该是:

 DataFormatter fmt = new DataFormatter(); String valueAsInExcel = fmt.formatCellValue(cell); 

这将根据在Excel中应用的格式化规则来格式化数字,所以应按照您的期望返回它

最后,Excel中的date自1900年或1904年以浮点数forms存储,这就是为什么您在date单元格中看到您所做的数字。