【问题标题】:writing old date with apache poi用 apache poi 写旧日期
【发布时间】:2016-05-12 09:25:08
【问题描述】:

我正在使用 apache poi 3.14 创建一个 excel 文件,该文件必须包含不同类型的数据,包括日期。

我的代码在大多数情况下都能正常工作。 在单元格中编写具体日期(java.util.Date)时遇到问题。 这是我的代码:

 Date date;

 // code where I get the value of date

 Cell currentCell = currentRow.createCell(fieldPos++);

 // line below doesn't work for date like '11/11/1811' but work for '11/11/2111'
 currentCell.setCellValue(date);

 currentCell.setCellStyle(myDateStyle);

假设我有 3 个日期要写:

  • 01/01/2009
  • 2111 年 11 月 11 日
  • 11/11/1811

我的 excel 文件将如下所示:

| 2009 年 1 月 1 日 | 2111 年 11 月 11 日 | 空白单元格 |

当日期等于 11/11/1811 时 currentCell.setCellValue(date) 行将值设置为 -1,因此在我的 excel 文件中它显示为空白(根据我的 dateStyle)

为什么它在特定日期不起作用,我该如何解决?

【问题讨论】:

    标签: java excel date apache-poi


    【解决方案1】:

    找到原因了!

    Apache Poi 的 setCellValue(Date d) 尝试将给定的 java.util.Date 转换为 excel "datenumber" :

    Excel 将日期和时间存储为一个数字,表示自 1900 年 1 月 0 日以来的天数,加上 24 小时制的小数部分:ddddd.tttttt。这称为序列日期或序列日期时间。

    这就是为什么当给定 1900 年之前的日期时,setCellValue 会将值设置为 -1,因为它无法进行转换操作。

    解决了在 setCellValue(Date d) 设置 -1 的情况下使用 Date.toString() 调用 setCellValue(String s) 的问题,唯一剩下的问题是我更改了数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-03
      • 1970-01-01
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 2014-11-07
      • 1970-01-01
      相关资源
      最近更新 更多