从excel读取时获取空指针异常java XSSFCell cell = row.getCell(j);

时间:2014-01-16 08:07:49

标签: java apache-poi

private String[][] data;

// to read from excel file

public void readFile() throws IOException {

    // Path to the excel file
    // File datafile = new File("C:\\Users\\atomar\\Documents\test.xlsx");
    // A Buffered File Input Stream to read the data
    FileInputStream f = new FileInputStream(
            "C:\\Users\\atomar\\Documents\\test.xlsx");
    System.out.println("file found");
    // InputStream fis = new BufferedInputStream(new FileInputStream("f"));
    // We create a workbook which represents the excel file
    XSSFWorkbook book = new XSSFWorkbook(f);

    // Next a sheet which represents the sheet within that excel file
    XSSFSheet sheet = book.getSheet("Sheet1");

    // No of rows in the sheet
    int rowNum = sheet.getLastRowNum() + 1;
    System.out.println("rowNum");

    // No of columns in the sheet
    int colNum = sheet.getRow(0).getLastCellNum();

    // A Two dimensional array of Strings which represents the data in the
    // sheet
    data = new String[rowNum][colNum];
    {

        for (int i = 0; i < rowNum; i++) {
            // Get the row
            XSSFRow row = sheet.getRow(i);

        for (int j = 0; j < colNum; j++) {
            // Get the columns or cells for the first row and keep
                // looping
                // for the other rows
        XSSFCell cell = row.getCell(j);

        // Make a call to the method cellToString which actually
                // converts the cell contents to String
                data[i][j] = cellToString(cell);

            //  data[i][j] = value;

    // Here is where you write the logic to handle the data.I am
                // just printing out the contents here.

                //System.out.println("The value is " + data[i][j]);


            }
        }

我在这里调用该功能

public void InterestedParty() throws InterruptedException {
    try {
        readFile();
    } catch (IOException e1) {
    }
}

获取错误:此类单元格不支持 我从输入excel文件中删除了两行数据,然后在它工作正常之前就开始了。但是现在我已经完全删除了那些行,那里也有问题

2 个答案:

答案 0 :(得分:6)

如果没有数据,XSSFCell将为null。检查它是否为null。致电cellToString()方法后。

    XSSFCell cell = row.getCell(j);
    if(cell != null) {
        data[i][j] = cellToString(cell);
    } else {
        // if you would like to set value when cell is null
        row.createCell(j).setCellValue(your value);
    }

答案 1 :(得分:0)

您可以拥有一行数据,一行是空行,然后是另一行数据。如果未定义,则可以将中间行视为null,因此我的建议是对行使用迭代器。
RowIteratior这是一个好的开始。
另外,一旦有了行,就可以使用单元迭代器迭代单元格。请记住,未定义的单元格将被视为空并跳过,但空单元格不为空!
Cell iterator在这里被记录。
您的方法也很好,但在处理对象之前,您需要在每次迭代时检查空值或为空。