Apache POI时间单元 [英] Apache POI Time Cell

查看:139
本文介绍了Apache POI时间单元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检测单元格格式是日期,时间还是日期时间。

我的代码是:

I need to detect, whether cell format is Date, Time or Datetime.
My code is:

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

我使用ApachePOI 3.6

I use ApachePOI 3.6

推荐答案

我在POI中看不到内置的方法。首先,在时间,日期和日期时间之间似乎没有明确的区别。这些值只是存储为数字,并应用格式显示。

I don't see a built-in way to do this easily in POI. First, there doesn't seem to be a clear distinction between "Time", "Date", and "Datetime". The values are just stored as numbers and a format is applied to display it.

您可以做的一件事是获取单元格的样式( HSSFCellStyle ),然后编写自己的方法,读取 style.getDataFormatString() style.getDataFormat()并根据您定义的格式告诉您格式是否属于时间,日期或日期时间类别。第二种方法返回一个 int ,因此可能会更容易使用。

One thing you could do is get the style of the cell (HSSFCellStyle), then write your own method that reads either style.getDataFormatString() or style.getDataFormat() and tells you whether the format falls in the "Time", "Date", or "Datetime" category depending on how you define them. The second method returns an int so it might be easier to work with.

例如,下面突出显示的格式具有[$ -F400] h:mm:ss\ AM / PM和<$​​ c $ c> int 值为166的字符串数据格式。

For example, the format highlighted below has a String data format of "[$-F400]h:mm:ss\ AM/PM" and an int value of 166.

我假设这是Datetime格式的意思,因为它是Excel的内置格式之一,显示日期和时间。

I'm assuming this is what you mean by "Datetime" format, as it's one of Excel's built-in formats that displays both the date and the time.

这种方法的缺点是我不希望它可以使用具有自定义日期/时间格式的单元格。

The drawback of this approach is that I wouldn't expect it to work with cells that have custom date/time formats.

这篇关于Apache POI时间单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆