null pointer exception apache poi

前端 未结 2 1309
借酒劲吻你
借酒劲吻你 2021-01-11 14:47

hi we\'ve been reading xls and xlsx file using apache poi ing our java program, the problem is we are getting null pointer exception with two reasons.. the first 1 is the bl

相关标签:
2条回答
  • 2021-01-11 15:21

    This my way to avoid Cell NullPoiterException.
    Can you try it. Good luck!

    /**
         * Get string value of {@link Cell} object
         * 
         * @param cell
         *          {@link Cell} object
         * @return String value of {@link Cell} object
         */
        private static String getCellValueString(Cell cell) {
            String value="";
            if(cell!=null) {
                switch(cell.getCellType()){
                    case Cell.CELL_TYPE_BOOLEAN:
                        value=String.valueOf(cell.getBooleanCellValue());
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        value=BigDecimal.valueOf(
                            cell.getNumericCellValue()).toPlainString();
                        break;
                    case Cell.CELL_TYPE_STRING:
                        value=String.valueOf(cell.getStringCellValue());
                        break;
                    case Cell.CELL_TYPE_FORMULA:
                        value=String.valueOf(cell.getCellFormula());
                        break;
                    case Cell.CELL_TYPE_BLANK:
                        value="";
                        break;
                }
            } else {
                logger.error("Cell is null");
            }
            return value.trim();
        }
    
    0 讨论(0)
  • 2021-01-11 15:27

    The issue is that you never test if the cell is null!

    if (cell == null)
    {
       System.out.println("Cell is Empty in Column:" + cols);
    
    } else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
    {
       //code
    }
    

    As a general matter, you should be careful while handling Cell.getCellType() function, since an empty cell could be either null or be a CELL_TYPE_BLANK.

    0 讨论(0)
提交回复
热议问题