【问题标题】:How to read Excel cell having Date with Apache POI?如何使用 Apache POI 读取具有日期的 Excel 单元格?
【发布时间】:2011-03-10 01:52:16
【问题描述】:

我正在使用 Apache POI 3.6,我想读取一个日期类似于 8/23/1991 的 Excel 文件。

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

如何解决我的问题?

【问题讨论】:

  • 对于我的宠物项目,我将其更改为 excel 表中的 Text 列以规避此问题。

标签: java apache excel apache-poi


【解决方案1】:

注意:HSSFDateUtil 已弃用

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

更新:这是一个示例 - 您可以在上面的 switch case 代码中应用它。我正在检查并打印数字和日期值。在这种情况下,工作表中的第一列有日期,因此我使用 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

【讨论】:

  • 我无法获取任何值...如果您可以指定代码 sn-p,那就太好了...
  • 调用 DateUtil.isCellDateFormatted() 将在将您的代码从 HSSF 和 XSSF 中释放出来的方式上领先一步。通过使用全局父代而不是依赖 XLS/XLSX 的 HSSF/XSSF 子代,您可以使您的代码更加通用。
  • 请调整或删除第二个链接。它返回 404 错误。
  • HSSFDateUtil 在版本 4.1.2 中已弃用
  • HSSFDateUtil代替DateUtilHSSFDateUtil的父类)
【解决方案2】:

是的,我了解您的问题。 如果难以识别单元格有 Numeric 或 Data 值。

如果您想要在 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 

【讨论】:

  • 如何将其格式化为 ISO 格式? (YYYY-MM-DD)
【解决方案3】:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;


Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
if(cell.getCellTypeEnum() == CellType.NUMERIC||cell.getCellTypeEnum() == CellType.FORMULA)
   {
    

 String cellValue=String.valueOf(cell.getNumericCellValue());
     if(HSSFDateUtil.isCellDateFormatted(cell))
      {
          DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
          Date date = cell.getDateCellValue();
          cellValue = df.format(date);
       }
          System.out.println(cellValue);
    }

【讨论】:

  • 请在您的答案中添加更多上下文。对于正在阅读您答案的每个人来说,仅仅编写代码作为答案可能并不那么清楚。
  • 这里使用 getDateCellValue 作为其他答案,但也使用 SimpleDateFormat 格式化大多数用户想要的 Date 值
【解决方案4】:

对于读取日期单元格,到目前为止,此方法已被证明是稳健的:

private LocalDate readCellAsDate(final Row row, final int pos) {
    if (pos == -1) {
        return null;
    }
    final Cell cell = row.getCell(pos - 1);
    if (cell != null) {
        cell.setCellType(CellType.NUMERIC);
    } else {
        return null;
    }
    if (DateUtil.isCellDateFormatted(cell)) {
        try {
            return cell.getDateCellValue().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        } catch (final NullPointerException e) {
            logger.error(e.getMessage());
            return null;
        }
    }
    return null;
}

【讨论】:

    【解决方案5】:

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

    【讨论】:

      【解决方案6】:

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

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

      【讨论】:

      • 我在 POI 中几乎实现了很多东西,很抱歉,我不能仅仅为了这个。。一定有什么。但是,谢谢你 duffymo
      • 无法切换到 JExcel 时,DateUtils 会帮您解决
      • 该链接已失效,但WayBack 仍可访问。即便如此,我没有看到任何提及 DateUtils。
      • 我想,HSSFDateUtil 是 DateUtil 的意思。
      【解决方案7】:

      如果您知道手机号码,那么我建议您使用 getDateCellValue() 方法 这是一个对我有用的例子 - java.util.Date 日期 = row.getCell().getDateCellValue(); System.out.println(date);

      【讨论】:

        【解决方案8】:

        试试这个代码。

        XSSFWorkbook workbook = new XSSFWorkbook(new File(result));
            XSSFSheet sheet = workbook.getSheetAt(0);
        
            // Iterate through each rows one by one
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                // For each row, iterate through all the columns
                Iterator<Cell> cellIterator = row.cellIterator();
        
                while (cellIterator.hasNext()) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_NUMERIC:
                        if (cell.getNumericCellValue() != 0) {
                            //Get date
                            Date date = row.getCell(0).getDateCellValue();
        
        
        
                            //Get datetime
                            cell.getDateCellValue()
        
        
                            System.out.println(date.getTime());
                        }
                        break;
                    }
                }
            }
        

        希望是帮助。

        【讨论】:

          猜你喜欢
          • 2017-11-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多