写这篇文章的由来:1.遇到了这个问题 2.通过搜索没有合适的解决方案 3.笔者发现了问题的根源,下面进入正题:
近期在使用POI解析excel日期单元格时出现了一个问题,通过getDateCellValue获取到的时间不对:都是1900年的日期,可笔者已经将日期单元格格式设置为日期格式,为什么读取时间不对呢?
最终发现是excel自身的问题,经过跟踪获取了该单元格以下数据:
<xml-fragment r="G6" s="3" t="s"xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:main="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<main:v>20</main:v>
</xml-fragment>
正确的是:
<xml-fragment r="G3" s="3" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:main="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<main:v>42685</main:v>
</xml-fragment>
相信大家可以看到区别了:产生问题的根源在于虽然设置了该excel单元格为日期格式,而且跟踪调试,发现POI读取该单元格的CellStyle调用getDataFormatString方法返回结果为[$-17804]yyyy/m/d;@,但是最奇怪的地方在于通过getCellType获取该单元格的格式却是:HSSFCell.CELL_TYPE_STRING
谜底揭开:虽然我们通过office设置该单元格为日期格式,但是该单元格格式依然是HSSFCell.CELL_TYPE_STRING(字符串)格式,所以通过getDateCellValue获取到的日期不对,笔者还发现:在日期单元格按下回车键后,该单元格由最初的左对齐(字符串默认对齐方式)变为右对齐(日期默认对齐方式),变为右对齐后再通过getDateCellValue就能获取到正确的日期,这算是POI与EXcel兼容不太好的地方