如何读取Excel与Apache POI有日期的细胞? [英] How to read Excel cell having Date with Apache POI?

查看:270
本文介绍了如何读取Excel与Apache POI有日期的细胞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Apache POI 3.6,我想读它有这样一个日期的Excel文件 1991年8月23日

I'm using Apache POI 3.6, I want to read an excel file which has a date like this 8/23/1991.

 switch (cell.getCellType()) {

   ...
   ...

   case HSSFCell.CELL_TYPE_NUMERIC:
     value = "NUMERIC value=" + cell.getNumericCellValue();
     break;

   ...

 }

但它需要的数值类型,并返回这样的值 33473.0

我试图用数字单元格类型,虽然没有运气。

I've tried to use Numeric Cell Type although with no luck.

dbltemp=row.getCell(c, Row.CREATE_NULL_AS_BLANK).getNumericCellValue();

if (c == 6 || c == 9) {
    strTemp= new String(dbltemp.toString().trim());

    long tempDate = Long.parseLong(strTemp);
    Date date = new Date(tempDate);

    strVal = date.toString();
}

我怎样才能解决我的问题?

How can I fix my problem?

推荐答案

如果你知道哪些细胞即列位置每一行中说,0将是一个日期,你可以去
row.getCell(0).getDateCellValue()直接。结果
<一href=\"http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html#getDateCellValue()\">http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html#getDateCellValue()

If you know which cell i.e. column position say 0 in each row is going to be a date, you can go for row.getCell(0).getDateCellValue() directly.
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html#getDateCellValue()

更新:下面是一个例子 - 你可以在你的交换机的情况下code以上应用此。我检查并打印数字和日期值。在这种情况下,我的表中的第一列的日期,所以我用row.getCell(0)。

UPDATE: Here is an example - you can apply this in your switch case code above. I am checking and printing the Numeric as well as Date value. In this case the first column in my sheet has dates, hence I use row.getCell(0).

您可以在开关的情况下直接使用如果(HSSFDateUtil.isCellDateFormatted .. code座。

You can use the if (HSSFDateUtil.isCellDateFormatted .. code block directly in your switch case.

if (row.getCell(0).getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
    System.out.println ("Row No.: " + row.getRowNum ()+ " " +
        row.getCell(0).getNumericCellValue());

    if (HSSFDateUtil.isCellDateFormatted(row.getCell(0))) {
        System.out.println ("Row No.: " + row.getRowNum ()+ " " + 
            row.getCell(0).getDateCellValue());
    }
}

的输出是

Row No.: 0 39281.0
Row No.: 0 Wed Jul 18 00:00:00 IST 2007
Row No.: 1 39491.0
Row No.: 1 Wed Feb 13 00:00:00 IST 2008
Row No.: 2 39311.0
Row No.: 2 Fri Aug 17 00:00:00 IST 2007

这篇关于如何读取Excel与Apache POI有日期的细胞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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