用apache poi写旧的date

我使用apache poi 3.14来创build一个excel文件,它必须包含不同types的数据,包括date。

我的代码在大多数情况下工作正常。 在单元格中编写特定date(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); 

假设我有三个date来写:

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

我的Excel文件将如下所示:

| 01/01/2009 | 11/11/2111 | blankcell |

当date等于11/11/1811时,currentCell.setCellValue(date)将该值设置为-1,所以在我的excel文件中显示为空(根据我的dateStyle)

为什么它不能在特定的date工作,我该如何解决这个问题?

find了这个原因!

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

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

这就是为什么在1900年之前给定一个datesetCellValue将值设置为-1导致它不能进行转换操作。

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