【问题标题】:Unable to read date which is of numerical type from excel using poi [duplicate]无法使用 poi 从 excel 中读取数字类型的日期 [重复]
【发布时间】:2016-01-22 04:16:22
【问题描述】:

我正在尝试使用 POI 读取 excel 文件。 excel第一列是日期(字符串类型),第二列是字符串。

所以,如果我这样做cell.getStringCellValue(),我的代码就可以正常工作

但是,Excel 中有一个特定的行,其中两列都是数字类型。

因此我得到:

java.lang.IllegalStateException: Cannot get a text value from a numeric cell

System.out.println(dateCell.getNumericCellValue());
System.out.println(ctrCell.getNumericCellValue());

打印出来:

42360.0
0.3227586206896551

但在 excel 中,我可以将其视为:12/22/2015 和 32.2758620689655%

请建议我如何仅将日期读取为 2015 年 12 月 22 日,而不是数字单元格中的 42360.0。

任何帮助将不胜感激!

【问题讨论】:

    标签: java excel apache-poi


    【解决方案1】:

    试试这个:

              Cell cell = row.getCell(colPos,Row.RETURN_BLANK_AS_NULL);
                                if (cell == null) {
    
                                value = "";
    
                                } 
                                else {
    
                                value = cell.toString().trim();
                                switch (cell.getCellType()) {
                                case  XSSFCell.CELL_TYPE_NUMERIC:
    
                                value = BigDecimal.valueOf(cell.getNumericCellValue()).toPlainString().trim();
    
                                if (DateUtil.isCellDateFormatted(cell)) {
                                double val = cell.getNumericCellValue();
                                Date date = DateUtil.getJavaDate(val);
    
                                String dateFmt = null;
    
    
                                if(cell.getCellStyle().getDataFormat()==14){
                                    dateFmt = "dd/mm/yyyy";
    
                                    value = new CellDateFormatter(dateFmt).format(date);
    
                                }
                                else{
                                    DataFormatter fmt = new DataFormatter();
                                    String valueAsInExcel = fmt.formatCellValue(cell);
    
    
    
                                        value = valueAsInExcel;
    
    
                                }
    
                        }
    
                                break;
    
                                case XSSFCell.CELL_TYPE_STRING:
                                value = cell.getStringCellValue().trim();
                                break;
    
                                case XSSFCell.CELL_TYPE_BLANK:
                                value = "";
                                break;
    
                                default:
                                break;
                                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多