XLSX 自定义日期格式读取为字符串

Ond*_*kar 1 java excel xlsx apache-poi

我有XLSX这个日期在单元格:03-09-2014当我使用Apache POI读取XLSX细胞,它这样写道:41883.0

这就是我这样做的方式:

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

由于我已将所有单元格转换为 String 类型,因此我希望日期不会变形...

有什么解决办法吗? 包含日期的单元格上的 apache poi DataFormatter 这是解决方案:)

Gag*_*arr 5

为什么?为什么哦,为什么哦,你为什么要开始写那个代码?它在很多层面上都是错误的,可能在 Stackoverflow 上每三个 Apache POI 问题就涵盖了 :( 哦,JavaDocs 中明确建议不要这样做......

您有两种选择。如果您想完全控制读取值,请按照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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想“给我最接近该单元格在 Excel 中的外观的字符串”,那么您需要使用DataFormatter 类该类提供了读取应用于单元格的 Excel 格式规则的方法,然后重新 -在 Java 中创建(尽其所能)那些

你的代码应该是:

DataFormatter fmt = new DataFormatter();

String valueAsInExcel = fmt.formatCellValue(cell);
Run Code Online (Sandbox Code Playgroud)

这将根据 Excel 中应用的格式规则格式化数字,因此应该按预期返回它

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