Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use rowiterator and iterator for iterating through the rows of an excel sheet

The code to read the contents of an excel spreadsheet (.xlsx) is included below. To iterate thru each row, I'm using iterator() method of sheet object, this works well. Also if I use rowIterator() method, it also works well.

What is the difference between these 2 functions and when to use which.

{

FileInputStream fis = new FileInputStream(new File("E:\\readexcel.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sh = wb.getSheetAt(0);
Iterator<Row> rowIterator = sh.iterator(); // sh.rowIterator(); -- also works well
while(rowIterator.hasNext()){               
    Row row = rowIterator.next();               
    Iterator<Cell> cellIterator = row.iterator(); //row.cellIterator();-- also works well               
    while(cellIterator.hasNext()){                  
        Cell cell = cellIterator.next();
        System.out.print(cell.getStringCellValue()+"\t");
    }
                System.out.println("");
}

}
like image 334
karusai Avatar asked Sep 18 '25 02:09

karusai


1 Answers

The documentation for XSSFSheet says this:

rowIterator - Returns an iterator of the physical rows

iterator - Alias for rowIterator() to allow foreach loops

So basically they return the same values, but the second was added to support Java's for-each loop. In other words, instead of getting the iterator and running while loop, you could directly run for-each loop, which makes code shorter and more readable:

FileInputStream fis = new FileInputStream(new File("E:\\readexcel.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sh = wb.getSheetAt(0);
for(Row row : sh) {             
    for(Cell cell : row) {
        System.out.print(cell.getStringCellValue()+"\t");
    }
}
...  
like image 93
ytrewq Avatar answered Sep 20 '25 17:09

ytrewq