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

标签 java excel apache-poi xlsx

我在单元格中有这个日期的 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() + ";");
            }

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

有什么解决办法吗? apache poi DataFormatter on cell containing date 这就是解决方案:)

最佳答案

为什么?为什么哦为什么哦为什么你要先写那段代码?它在很多层面上都是错误的,正如 Stackoverflow 上每三个 Apache POI 问题所涵盖的那样:( 哦,它是 explicitly advised against in the JavaDocs ....

您有两种选择。如果您想完全控制读取值,请遵循 instructions in the Apache POI documentation on reading cell values ,然后编写如下代码:

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();
        }
    }
}

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

您的代码应该是:

DataFormatter fmt = new DataFormatter();

String valueAsInExcel = fmt.formatCellValue(cell);

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

最后,自 1900 年或 1904 年以来,Excel 中的日期存储为 float ,这就是您在日期单元格中看到数字的原因。

关于java - XLSX 自定义日期格式读取为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26378452/

相关文章:

java - 使用 Apache POI 读取/写入同一 Excel 文件

java - 有没有办法使用 Apache poi 从给定的 PowerPoint 文件中准确获取演讲者笔记?

java - 如何在 Lombok 中调用 super 构造函数

java - 在 Java 中定义错误代码/字符串的最佳方法?

java - 如何解决: java. io.IOException: Stream closed

vba - 使用多个变量重复 IF 语句

Java 调用堆栈检查和操作

VBA编写函数及返回值

excel - 如何创建在 EPPlus 中计算值的 DataField?

java - POI - null 后文件意外结束