0

我正在迭代一列值,直到它出现空白。我需要收集整个列并存储它,而不需要其他值。我试图检查空白、null、0、"" 和 CELL_TYPE_BLANK (int = 3),但我无法避免空指针异常。代码片段和错误如下。我能做些什么?这不是整个方法或程序,只是相关部分。

String s = list[i];
//find the directory from the list array to locate the file
InputStream input = new FileInputStream(s);
//create a new workbook object to hold the excel file
Workbook wb = new XSSFWorkbook(input);
//create an arbitrary starting location
int column = 2; //absolutely the correct number
int rownum = 10;
//get the value from the first sheet
org.apache.poi.ss.usermodel.Sheet insheet = wb.getSheetAt(0);       
//of the second columm
Row row = insheet.getRow(rownum);
//in the 11th row (arbitrary number used to reduce iterations and skip whitespace)
Cell cell = row.getCell(column); 
System.out.println("Skimming sheet: " + insheet.getSheetName());
//iterate until the very end of the column is found
System.out.println("Cell value B" + (rownum-1) +  ": " + cell);

//3 denotes CELL_TYPE_BLANK
while (cell.getCellType() != 3 ) {
    //go to the next location
    //update to the next cell
    System.out.println("Cell value B" + rownum +  ": " + cell);
    row = insheet.getRow(rownum);
    if(row.getCell(column).getCellType() != 3){
        cell = row.getCell(column); //error occurs here, line 241
    }
    rownum++;
}


Exception in thread "main" java.lang.NullPointerException
    at FileTest.skim(FileTest.java:241)
    at FileTest.main(FileTest.java:121)
4

2 回答 2

2

你得到错误是因为你试图访问的行是空的,而不是单元格。您想看看Apache POI 迭代器示例。

//taken from the example
Sheet sheet = wb.getsheetat(0);
for (Iterator<Row> rit = sheet.rowiterator(); rit.hasnext(); ) {
    Row row = rit.next();
    //now, based in your needs
    Cell cell = row.getCell(column);
    //do what you need with the row-column
}
于 2012-05-06T18:40:04.400 回答
0

将 for 循环中的行迭代到最后一行,这将防止遇到该异常:

 for(int i =0 ; i< insheet.getLastRowNum(); i++){
//do stuff
}
于 2012-05-06T18:41:47.457 回答