如果包含日期的单元格的格式设置为默认日期格式 (Short Date
),则文件中仅存储格式 id 0xE (14)。看https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html. The *.xlsx
文件仅包含
<xf numFmtId="14" ... applyNumberFormat="1"/>
in styles.xml
。没有什么特别的formatCode
为此保存numFmtId
.
那么这将如何显示在Excel
取决于系统的区域设置。
例如我的德语 Windows 系统numFmtId="14"
将显示为TT.MM.JJJJ
如中设置的Region and Language
设置:
在英语英国 Windows 系统中,这将是DD/MM/YYYY
默认情况下。
但如果你改变设置Short Date
在系统设置中,JJJJ-MM-TT
例如,此格式也将显示在 Excel 中numFmtId="14"
.
因此,要了解 Excel 将如何准确地显示日期numFmtId="14"
,需要知道确切的 Windows 系统设置Region and Language
.
因此,如果不知道系统的区域设置,apache POI 也无法知道如何显示它,因为该文件不包含有关此的信息。所以它会假设en-us
语言环境。这导致m/d/yy
日期。
您可以检查是否使用了格式 id 14,如果使用了,请定义您自己的默认日期格式。
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
System.out.println(date);
String dateFmt = "";
if (cell.getCellStyle().getDataFormat() == 14) { //default short date without explicit formatting
dateFmt = "dd/mm/yyyy"; //default date format for this
} else { //other data formats with explicit formatting
dateFmt = cell.getCellStyle().getDataFormatString();
}
System.out.println("dateFmt " + dateFmt);
String value = new CellDateFormatter(dateFmt).format(date);
System.out.println("Date " + value);
}
需要明确的是:这一切都只是numFmtId="14"
cell.getCellStyle().getDataFormat() == 14
。所有其他日期格式都将具有明确的数据格式字符串cell.getCellStyle().getDataFormatString()
因此 POI 可以像在 Excel 中一样显示它们。
See POI DataFormatter 对于日期单元格返回 2 位年份而不是 4 位年份如何使用DataFormatter
解决这个问题。