POI通过getDateCellValue读取日期

11 篇文章 1 订阅

      写这篇文章的由来: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兼容不太好的地方


推荐阅读:http://blog.csdn.net/john1337/article/details/78646058


  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值