Java 空指针异常apache poi

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18072847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:11:16  来源:igfitidea点击:

null pointer exception apache poi

javaexcelnullpointerexceptionapache-poi

提问by y.reyes

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 blank cell which we already solved and the other one is when we are choosing a certain column that doesn't have any record..

嗨,我们一直在使用 apache poi ing 我们的 java 程序读取 xls 和 xlsx 文件,问题是我们得到空指针异常有两个原因..第一个是我们已经解决的空白单元格,另一个是当我们正在选择没有任何记录的某个列..

our program ask for the path of the excel file then the specific sheet number of the file and the specific column number of the sheet you want to read.. here is the code for reading xls file

我们的程序询问excel文件的路径,然后是文件的具体工作表编号和您要阅读的工作表的具体列号..这是读取xls文件的代码

public void readXLSFile()throws IOException{
    InputStream ExcelFileToRead = new FileInputStream(path);
    HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);


    HSSFSheet sheet=wb.getSheetAt(sheetname);
    HSSFRow row; 
    HSSFCell cell;

    Iterator rows = sheet.rowIterator();

            list1.clear();

    while (rows.hasNext())
    {
                   headers.clear();
        row=(HSSFRow) rows.next();

                // Iterator cells = row.cellIterator();

                    headers.add("contents");


            cnt = cnt+1;

            cell = row.getCell(cols);
            if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
            {
                //System.out.println(cell.getStringCellValue()+"(string)");
                list.add(cell.getStringCellValue());
                                    d.add(cell.getStringCellValue());
                                    list1.add(new KeyValuePair(cell.getStringCellValue(),""));
            }
            else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
            {
                //System.out.println(cell.getNumericCellValue()+"(numeric)");
                double num = cell.getNumericCellValue();
                String num2 = String.valueOf(num);
                list.add(num2);
                                     d.add(num2);
                                     list1.add(new KeyValuePair(num2,""));

            }
            else if(cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN)
            {
                //System.out.println(cell.getBooleanCellValue()+"(boolean)");
                String bool = String.valueOf(cell.getBooleanCellValue());
                list.add(bool);
                                     d.add(bool);
                                     list1.add(new KeyValuePair(bool,""));
            }
            else
            {
                //U Can Handel Boolean, Formula, Errors
            }


        //System.out.println();
    }
        arrey = list.toArray(new String[list.size()]);
                    data.add(d);
                   // System.out.println(data);


                     model = new DefaultTableModel();
                     table_1.setModel(model);


                   table_1.setModel(model);
                      model.setColumnIdentifiers(new String[] {"row","contents"});

                     for (KeyValuePair p : list1){


                       int nor=table_1.getRowCount();

                       int n2 = nor +1;
                        n1 = Integer.toString(n2);
                     //  model.addColumn(new String [] {n1});   


                       model.addRow(new String[] {n1,p.key, p.value});


                     }
                  //   model.addColumn(new String[] {n1});

}

the variable sheetname is for the excel file's sheet number

变量 sheetname 用于 Excel 文件的工作表编号

HSSFSheet sheet=wb.getSheetAt(sheetname);

and the variable cols is for the specific column you want to read

变量 cols 用于您要读取的特定列

cell = row.getCell(cols);

we can read the first column of every sheet and also the second column of the second sheet but when i edited my test file the program now can only read the first column of every sheet.. the error is null pointer exception..wish you could help thanks in advance

我们可以读取每张工作表的第一列以及第二张工作表的第二列,但是当我编辑我的测试文件时,程序现在只能读取每张工作表的第一列..错误是空指针异常..希望你能帮助提前致谢

采纳答案by ArtiBucco

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 nullor be a CELL_TYPE_BLANK.

作为一般事项,你应该在处理小心Cell.getCellType()功能,因为空单元格可能是因为存在null或者是CELL_TYPE_BLANK

回答by iCrazybest

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

这是我避免 Cell NullPoiterException 的方法。
你可以试试吗。祝你好运!

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