如何使用 Apache POI 读取具有日期的 Excel 单元格?

新手上路,请多包涵

我正在使用 Apache POI 3.6,我想读取一个日期如下的 Excel 文件 8/23/1991

  switch (cell.getCellType()) {

   ...
   ...

   case HSSFCell.CELL_TYPE_NUMERIC:
     value = "NUMERIC value=" + cell.getNumericCellValue();
     break;

   ...

 }

但它采用数值类型并返回这样的值 33473.0

我试过使用数字单元格类型,虽然没有运气。

 dbltemp=row.getCell(c, Row.CREATE_NULL_AS_BLANK).getNumericCellValue();

if (c == 6 || c == 9) {
    strTemp= new String(dbltemp.toString().trim());

    long tempDate = Long.parseLong(strTemp);
    Date date = new Date(tempDate);

    strVal = date.toString();
}

我该如何解决我的问题?

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

阅读 1.3k
2 个回答

注意:不推荐使用 HSSFDateUtil

如果您知道哪个单元格,即每行中的列位置 0 将是日期,您可以直接选择 row.getCell(0).getDateCellValue()

http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html#getDateCellValue()

更新:这是一个示例 - 您可以在上面的 switch case 代码中应用它。我正在检查并打印数字和日期值。在这种情况下,我的工作表中的第一列有日期,因此我使用 row.getCell(0)。

您可以直接在您的开关盒中使用 if (HSSFDateUtil.isCellDateFormatted .. 代码块。

 if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
    System.out.println ("Row No.: " + row.getRowNum ()+ " " +
        row.getCell(0).getNumericCellValue());

    if (HSSFDateUtil.isCellDateFormatted(row.getCell(0))) {
        System.out.println ("Row No.: " + row.getRowNum ()+ " " +
            row.getCell(0).getDateCellValue());
    }
}

输出是

Row No.: 0 39281.0
Row No.: 0 Wed Jul 18 00:00:00 IST 2007
Row No.: 1 39491.0
Row No.: 1 Wed Feb 13 00:00:00 IST 2008
Row No.: 2 39311.0
Row No.: 2 Fri Aug 17 00:00:00 IST 2007

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

是的,我明白你的问题。如果难以识别单元格具有数字或数据值。

如果你想要在 Excel 中显示的格式的数据,你只需要使用 DataFormatter 类格式化单元格。

 DataFormatter dataFormatter = new DataFormatter();
String cellStringValue = dataFormatter.formatCellValue(row.getCell(0));
System.out.println ("Is shows data as show in Excel file" + cellStringValue);  // Here it automcatically format data based on that cell format.
// No need for extra efforts

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

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