Reading Excel Files

Harry · 24 Sep 2026 · 1 views
Log in to track your progress and mark lessons complete.

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();
    }
}

Reading rows and cells with DataFormatter

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 of getCell(i) when columns may be missing — otherwise you get null.
  • DataFormatter avoids the classic mistake of calling getStringCellValue() on a numeric cell (throws IllegalStateException).
  • WorkbookFactory.create(...) auto-detects .xls vs .xlsx.

Full runnable version: ReadExcelExample in the poi-examples repo.

Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in