获取字符串值,当我使用日期类型 (apache poi) 从 excel 读取时

Ser*_*hyi 7 java apache-poi simpledateformat xssf

我有一个正在阅读的xlsx 文件- Apache POI 库。

例如,在某些行中,我有这样的单元格值:

13 年 9 月 1 日 | 15136.00| 马特|......


我的目标是: 将行中的所有单元格读取为字符串值。但正如我所见,我无法将01-Sep-13读取为字符串,它只表示像 Date 类型 () 和 cell.getDateCellValue();


1)我可以以某种方式将 01-Sep-13 读为字符串:“01-Sep-13”;2)如果我有不同的日期模式(ddMMyyyy)和(dd-MMM-yy),我可以将日期值转换为字符串吗?

代码:

当我遍历行和单元格时,Apache POI 会分析每种单元格类型:

String normalizeCellType(Cell cell) {

    switch (cell.getCellType()) {
        case Cell.CELL_TYPE_STRING:
           return cell.getRichStringCellValue().getString());            
        case Cell.CELL_TYPE_NUMERIC:
            if (DateUtil.isCellDateFormatted(cell)) {

                Date date = cell.getDateCellValue(); ????????????
                System.out.println(date);

            } else {

                ....
            }
            break;
        case Cell.CELL_TYPE_BOOLEAN:
           return ....
        case Cell.CELL_TYPE_FORMULA:
           return ....
        default:
            System.out.println();
    }
}
Run Code Online (Sandbox Code Playgroud)

Kee*_*san 5

您可以获取 cell#getDateCellValue() 的返回值并使用 SimpleDateFormat 将其转换为 String 实例

 // Create an instance of SimpleDateFormat used for formatting 
    // the string representation of date (month/day/year)
    DateFormat df = new SimpleDateFormat("dd/MM/yyyy");

    // Get the date today using cell.getDateCellValue() 
    Date today = cell.getDateCellValue()       
    // Using DateFormat format method we can create a string 
    // representation of a date with the defined format.
    String reportDate = df.format(today);
Run Code Online (Sandbox Code Playgroud)

您可以获取字符串格式的日期值 - 31/10/2013。希望这可以帮助


rge*_*man 4

您有 2 个选择:

  • 使用 Java 的SimpleDateFormat将返回的格式设置DateString您选择的格式。您可以SimpleDateFormat为您需要的每种不同格式提供一个实例。
  • 使用Apache POI的DataFormatter直接格式化Cell