2010-06-10 213 views
3

我需要檢測,單元格格式是日期,時間還是日期時間。
我的代碼是: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

回答

0

我沒有看到一個內置的方式在POI做到這一點很容易。首先,「時間」,「日期」和「日期時間」之間似乎沒有明顯的區別。這些值只是以數字形式存儲,並且應用了一種格式來顯示它。

有一兩件事你可以做的是讓細胞(HSSFCellStyle)的風格,然後再編寫自己的方法讀取或者style.getDataFormatString()style.getDataFormat(),並告訴你的格式是否屬於「時間」,「日期」,或者「日期時間「類別取決於您如何定義它們。第二種方法返回int,因此可能更容易處理。

例如,突出顯示的格式下面具有一個字符串數據格式 「[$ -F400] H:MM:SS \ AM/PM」 和166.

Excel Date/Time Format

我的int值假設這就是你所說的「日期時間」格式,因爲它是Excel的內置格式之一,可以顯示日期和時間。

這種方法的缺點是,我不希望它與自定義日期/時間格式的單元格一起工作。

0

在我看來,我們能做的唯一好事就是 - 看看時間部分是否具有零以外的價值。 我試圖用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