0

我正在疯狂地尝试使用Apache POI从 Java 解析 Excel,并且我发现以下问题解析包含日期的特定列。

这是我的 Excel 文件中的列:

在此处输入图像描述

如您所见,此列包含日期字段,但此列的某些单元格包含数字值,其他一些单元格包含文本值(我可以使用TYPE() Excel 函数看到它)。我真的不知道这怎么可能,因为所有单元格都包含日期字段。有什么想法?

无论如何,在我的代码中,我试图以这种方式处理这种奇怪的情况:

if(currentRow.getCell(20) != null && !currentRow.getCell(20).toString().trim().isEmpty()) {
    
    if(currentRow.getCell(20).getCellType().toString().equals("STRING")) {
        System.out.println("Data sottoscrizione contratto è STRING: " + currentRow.getCell(20).toString());
        
    }
    else if(currentRow.getCell(20).getCellType().toString().equals("NUMERIC")) {
        System.out.println("Data sottoscrizione contratto è NUMERIC");
        String dateAsString = currentRow.getCell(20).toString();
        System.out.println("DATA SOTTOSCRIZIONE CONTRATTO: " + currentRow.getCell(20).toString());
        
        
    }
}

通过这种方式,我可以处理尝试转换为日期的两种情况。

这是我的问题。当它在 if NUMERIC案例中找到一个 Excel 数值时

并通过以下方式打印单元格值:

System.out.println("DATA SOTTOSCRIZIONE CONTRATTO: " + currentRow.getCell(20).toString());

我打印了与日期值16/10/2017相关的值16-ott-2017

这里有一些疑问:为什么我会以这种格式获得16/10/2017 之类的东西。

16-ott-2017应该是日期的意大利语格式。如何将其转换为合适的 Date 对象?

4

1 回答 1

2

邦乔诺!

您当前正在使用toString()单元格的方法,该方法在返回数值甚至日期时都不会很准确。它有时可能会起作用,但并非总是如此。

使用可以让您获得真正价值的方法,例如Cell.getNumericCellValue(), Cell.getDateCellValue()(已过时,因为它返回 a java.util.Date)或Cell.getLocalDateTimeCellValue(). 如果您的单元格仅包含文本,例如"16-ott-2020",请使用getStringCellValue()并将返回的值转换为 a LocalDate(或LocalDateTime取决于一天中的时间是否对您很重要)。

这是转换(到 a )的示例LocalDate

public static void main(String[] args) {
    // assuming you alread received the value as String
    String cellStringValue = "16-ott-2020";
    // provice a formatter that can parse Italian month names (or days of week)
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-uuuu", Locale.ITALIAN);
    // parse the String to a LocalDate
    LocalDate sediciOttobreDuemilaEVenti = LocalDate.parse(cellStringValue, dtf);
    // and print its default value
    System.out.println(sediciOttobreDuemilaEVenti);
    // alternatively use the same formatter for output
    System.out.println(sediciOttobreDuemilaEVenti.format(dtf));
}

该代码的输出是

2020-10-16
16-ott-2020
于 2020-09-21T12:21:19.550 回答