How to read Excel cell having Date with Apache POI?

前端 未结 8 2346
面向向阳花
面向向阳花 2020-11-28 03:57

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()) {

   ...
   ...

            


        
8条回答
  •  感动是毒
    2020-11-28 04:25

    For reading date cells this method has proven to be robust so far:

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

提交回复
热议问题