首页 文章

如何读取具有Apache POI日期的Excel单元格?

提问于
浏览
46

我正在使用Apache POI 3.6,我想阅读一个excel文件,其日期类似于 8/23/1991 .

switch (cell.getCellType()) {

   ...
   ...

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

   ...

 }

但是它采用数值类型并返回像 33473.0 这样的值 .

我试过使用数字细胞类型虽然没有运气 .

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

我该如何解决我的问题?

4 回答

  • 6

    如果你知道哪一个单元格,即每列中的列位置说0将是一个日期,你可以直接找到 row.getCell(0).getDateCellValue() .
    http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFCell.html#getDateCellValue()

    更新:这是一个示例 - 您可以在上面的开关案例代码中应用它 . 我正在检查并打印Numeric以及Date值 . 在这种情况下,我的工作表中的第一列有日期,因此我使用row.getCell(0) .

    您可以直接在开关盒中使用 if (HSSFDateUtil.isCellDateFormatted .. 代码块 .

    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
    
  • 1

    是的,我理解你的问题 . 如果难以识别,则单元格具有数值或数据值 .

    如果您希望在Excel中显示格式的数据,则只需使用DataFormatter类格式化单元格 .

    DataFormatter dataFormatter = new DataFormatter();
    String cellStringValue = dataFormatter.formatCellValue(row.getCell(0));
    System.out.println ("Is shows data as show in Excel file" + cellStringValue);  // Here it automcatically format data based on that cell format.
    // No need for extra efforts
    
  • 89

    您需要DateUtils:有关详细信息,请参阅this article .

    或者,更好的是,使用Andy Khan的JExcel而不是POI .

  • 0

    您可以使用CellDateFormatter以与excel单元格相同的格式获取日期 . 请参阅以下代码:

    CellValue cv = formulaEv.evaluate(cell);
    double dv = cv.getNumberValue();
    if (HSSFDateUtil.isCellDateFormatted(cell)) {
        Date date = HSSFDateUtil.getJavaDate(dv);
    
        String df = cell.getCellStyle().getDataFormatString();
    
        strValue = new CellDateFormatter(df).format(date); 
    }
    

相关问题