J'ai besoin d'itérer à la fin d'une colonne en Java sur une feuille Excel avec POI d'Apache

Je lance une colonne de valeurs jusqu'à ce qu'il frappe un blanc. Je dois rassembler toute la colonne et l'save, et pas d'autres valeurs. J'ai tenté de vérifier s'il-vous-plaît, null, 0, "" et CELL_TYPE_BLANK (int = 3), et je ne peux pas l'empêcher d'éviter une exception de pointeur nul. L'extrait de code et l'erreur sont ci-dessous. Que puis-je faire? Ce n'est pas la méthode ou le programme entier, juste la pièce pertinente.

Ssortingng 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) 

Vous obtenez l'erreur car la ligne que vous essayez d'accéder est nulle, et non la cellule. Vous souhaitez jeter un coup d'œil dans l'exemple d' Apoth POI Iterator .

 //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 } 

Iterate les lignes dans une boucle for jusqu'à la dernière ligne, ce qui empêchera de s'exécuter dans cette exception:

  for(int i =0 ; i< insheet.getLastRowNum(); i++){ //do stuff }