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("");
}
}
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");
}
}
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With