【问题标题】:I'm reading excel file using Apache POI. Unable to read Date. In excel,date format 2017-03-15 6:00(cell format=custom) & using poi,reading 42809.25我正在使用 Apache POI 读取 excel 文件。无法读取日期。在 excel 中,日期格式 2017-03-15 6:00(单元格格式=自定义)& 使用 poi,读取 42809.25
【发布时间】:2017-03-07 05:24:44
【问题描述】:

# 我正在使用 Apache POI 读取 excel 文件。无法读取日期。在 excel 中,日期格式 2017-03-15 6:00(单元格格式=自定义)& 使用 poi,读取 42809.25

cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
    int dataType = cell.getCellType();
    if (dataType == 0) {
        String cellData1 = NumberToTextConverter.toText(cell.getNumericCellValue());
        return cellData1;

    } else {
        String cellData = cell.getStringCellValue();
        return cellData;
    }

【问题讨论】:

    标签: apache-poi


    【解决方案1】:

    如果您知道哪个单元格,即每行中的列位置 2 将是日期,您可以直接选择 row.getCell(2).getDateCellValue()

    查看 POI 的 DateUtil 类中处理 Excelsheets 中日期的方法,DateUtil.isCellDateFormatted()

    或者你可以得到如下所示的日期

    if (DateUtil.isCellDateFormatted(cell))
    {
    try {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      cellValue = sdf.format(cell.getDateCellValue());
    
    } catch (ParseException e) {
            e.printStackTrace();
    }
    }
    

    【讨论】:

      【解决方案2】:

      感谢 Dhaval :) 我尝试使用您的代码和其他一些行。现在下面的代码对我有用。

      cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
                  if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
                      if (DateUtil.isCellDateFormatted(cell)) {
                          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                          String cellDate1 = sdf.format(cell.getDateCellValue());
                          return cellDate1;
                      } else {
                          String cellData2 = NumberToTextConverter.toText(cell.getNumericCellValue());
                          return cellData2;
                      }
                  } else {
                      String cellData = cell.getStringCellValue();
                      return cellData;
                  }
      

      【讨论】:

      • 如果你知道单元格索引,DateUtil 会减少代码,但你做的是 gud,
      • 是的。我包围了。我没有在这里粘贴 try and catch 块。无论如何谢谢:)
      • 很高兴为您提供帮助:)
      猜你喜欢
      • 2011-03-10
      • 1970-01-01
      • 2023-03-12
      • 2017-11-07
      • 1970-01-01
      • 2020-06-15
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多