前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >POI通过getDateCellValue读取日期

POI通过getDateCellValue读取日期

作者头像
johnhuster的分享
发布2022-03-29 13:56:46
7150
发布2022-03-29 13:56:46
举报
文章被收录于专栏:johnhuster

写这篇文章的由来:1.遇到了这个问题 2.通过搜索没有合适的解决方案 3.笔者发现了问题的根源,下面进入正题:

近期在使用POI解析excel日期单元格时出现了一个问题,通过getDateCellValue获取到的时间不对:都是1900年的日期,可笔者已经将日期单元格格式设置为日期格式,为什么读取时间不对呢?

最终发现是excel自身的问题,经过跟踪获取了该单元格以下数据:

代码语言:javascript
复制
<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>

正确的是

代码语言:javascript
复制
<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兼容不太好的地方

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016/11/29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档