Apache POI时间单元

我需要检测,单元格格式是date,时间还是date时间。
我的代码是:

if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { if ( ??? ) return "Time"; else if ( ??? ) return "Date"; else return "Datetime"; } } 

我使用ApachePOI 3.6

我没有看到在POI中轻松完成此操作的内置方法。 首先,“时间”,“date”和“date时间”之间似乎没有明显的区别。 这些值只是以数字forms存储,并应用一种格式来显示它。

你可以做的一件事是获取单元格样式( HSSFCellStyle ),然后编写自己的方法,读取style.getDataFormatString()style.getDataFormat()并告诉您格式是否落入“时间”,“date“或”date时间“类别,具体取决于您如何定义它们。 第二个方法返回一个int所以它可能更容易处理。

例如,下面突出显示的格式的string数据格式为“[$ -F400] h:mm:ss \ AM / PM”,并且其值为166。

Excel日期/时间格式

我假设这是你所说的“date时间”格式,因为它是Excel的内置格式之一,显示date和时间。

这种方法的缺点是,我不希望它与具有自定义date/时间格式的单元格一起工作。

在我看来,我们能做的唯一好事就是 – 看时间部分是否具有零以外的价值。 我试图使用style.getDataFormatString()style.getDataFormat()来检测这个,但他们的行为非常错误,我的testing用例。 这是我的代码:

 private boolean dateIncludesTime() // this method only tries to detect does time part exist, but it is not sure it will succeeed { Date javaDate= (Date)getValue(); if (javaDate.getHours() > 0 || javaDate.getMinutes() > 0) return true; int formatID = apacheCell.getCellStyle().getDataFormat(); if(formatID >= 18 && formatID <=22) // https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/BuiltinFormats.html return true; dateFormat = apacheCell.getCellStyle().getDataFormatString(); if(dateFormat.toLowerCase().contains("h")) // format mentions hours return true; return false; } 

以下是我得到的一些testing用例:

input03/21/2015 21:30 getDataFormatString()返回MM / DD / YY formatID = 165

input03/21/2016 getDataFormatString()返回MM / DD / YY formatID = 165

input2017-04-21 10:20 getDataFormatString()返回YYYY-MM-DD formatID = 166

input2017-05-21 getDataFormatString()返回YYYY-MM-DD formatID = 166