代码之家  ›  专栏  ›  技术社区  ›  Venkat

如何读取与apache poi有约会的excel单元?

  •  48
  • Venkat  · 技术社区  · 14 年前

    我使用的是ApachePOI3.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 年前
        1
  •  91
  •   giro coder_For_Life22    9 年前

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

    更新:这里有一个例子-您可以在上面的开关案例代码中应用它。我正在检查并打印数字和日期值。在这种情况下,工作表中的第一列有日期,因此我使用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
    
        2
  •  8
  •   Chintan    7 年前

    是的,我理解你的问题。 如果很难识别单元格有数值或数据值。

    如果希望数据采用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 
    
        3
  •  1
  •   duffymo    6 年前

    你需要dateutils:看 this article 详情。

    或者,更好的是,使用安迪·汗的Jexcel而不是POI。

        4
  •  0
  •   Abhishek Mishra    6 年前

    可以使用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); 
    }