获取字符串值,当我从具有日期类型的 excel 中读取时 (apache poi)

新手上路,请多包涵

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

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

2013 年 9 月 1 日 | 15136.00|马特|……


我的目标是: 将行中的所有单元格读取为字符串值。但正如我所见,我无法将 01-Sep-13 读取为字符串,它只表示像 Date type () 和 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();
    }
}

原文由 Sergii Lisnychyi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 904
2 个回答

您有 2 个选择:

  • 使用 Java 的 SimpleDateFormat 以您选择的格式将返回的 Date 格式化为 String 。对于您需要的每种不同格式,您可以拥有一个 SimpleDateFormat 实例。
  • 使用 Apache POI 的 DataFormatter 直接格式化 Cell

原文由 rgettman 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以获得 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);

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

原文由 Keerthivasan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题