Reading Excel Files
Harry
· 24 Sep 2026
· 1 views
Log in to track your progress and mark lessons complete.
Sponsored
Iterate Rows and Cells Safely
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
DataFormatter fmt = new DataFormatter(); // renders any cell as displayed in Excel
try (FileInputStream in = new FileInputStream("employees.xlsx");
Workbook wb = WorkbookFactory.create(in)) {
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
System.out.print(fmt.formatCellValue(cell) + "\t");
}
System.out.println();
}
}Things Beginners Get Wrong
sheet.getLastRowNum()returns the index of the last row, not the count; blank rows in between are skipped by the for-each loop.- Use
row.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)instead ofgetCell(i)when columns may be missing — otherwise you getnull. DataFormatteravoids the classic mistake of callinggetStringCellValue()on a numeric cell (throwsIllegalStateException).WorkbookFactory.create(...)auto-detects.xlsvs.xlsx.
Full runnable version: ReadExcelExample in the poi-examples repo.