Apache POI时间单元格

问题描述:

我需要检测,单元格格式是日期,时间还是日期时间。
我的代码是:Apache POI时间单元格

 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做到这一点很容易。首先,“时间”,“日期”和“日期时间”之间似乎没有明显的区别。这些值只是以数字形式存储,并且应用了一种格式来显示它。

有一两件事你可以做的是让细胞(HSSFCellStyle)的风格,然后再编写自己的方法读取或者style.getDataFormatString()style.getDataFormat(),并告诉你的格式是否属于“时间”,“日期”,或者“日期时间“类别取决于您如何定义它们。第二种方法返回int,因此可能更容易处理。

例如,突出显示的格式下面具有一个字符串数据格式 “[$ -F400] H:MM:SS \ AM/PM” 和166.

Excel Date/Time Format

我的int值假设这就是你所说的“日期时间”格式,因为它是Excel的内置格式之一,可以显示日期和时间。

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

在我看来,我们能做的唯一好事就是 - 看看时间部分是否具有零以外的价值。 我试图用style.getDataFormatString()style.getDataFormat()来检测这个,但是他们对我的测试用例表现非常不正确。这里是我的代码:

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; 
} 

这里就是我得到一些测试情况:

输入2015年3月21日21:30 getDataFormatString()返回MM/DD/YY formatID = 165

输入2016年3月21日getDataFormatString()返回MM/DD/YY formatID = 165

输入2017年4月21日10:20 getDataFormatString()返回YYYY-MM-DD formatID = 166

输入201 7-05-21 getDataFormatString()返回YYYY-MM-DD formatID = 166