簡體   English   中英

Apache POI時間單元

[英]Apache POI Time Cell

我需要檢測單元格格式是日期,時間還是日期時間。
我的代碼是:

        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”, int值為166。

Excel日期/時間格式

我假設這是“日期時間”格式的意思,因為它是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;
}

以下是我獲得的一些測試用例:

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

輸入03/21/2016 getDataFormatString()返回MM / DD / YY formatID = 165

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

輸入2017-05-21 getDataFormatString()返回YYYY-MM-DD formatID = 166

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM