To read an Excel file in Java, use Apache POI, the most widely used open-source library for Microsoft Office formats. Add the poi and poi-ooxml dependencies to your project, open the workbook with WorkbookFactory.create(), iterate the rows and cells, and close the workbook when done. For very large files, consider the streaming SXSSF reader instead of the standard XSSFWorkbook to keep memory use down.

What You'll Need

  • Java installed (a current LTS version is a sensible choice) and a build tool such as Maven or Gradle.
  • The Apache POI libraries: poi for the older .xls format and poi-ooxml for .xlsx files. Both are available from Maven Central.
  • An Excel file to test with — either .xls or .xlsx. The two formats need different POI classes, but WorkbookFactory handles both.
  • An IDE or text editor. Any will do.

Step-by-Step

  1. Add the dependencies. In Maven, add org.apache.poi:poi and org.apache.poi:poi-ooxml to your pom.xml. In Gradle, add the same coordinates to your build.gradle. Use the latest stable versions shown on Maven Central; exact version numbers change, so check there rather than copying an old one.
  2. Import the classes you need. At minimum: org.apache.poi.ss.usermodel.Workbook, WorkbookFactory, Sheet, Row, and Cell. These interfaces work for both .xls and .xlsx, which keeps your code format-agnostic.
  3. Open the file. Use WorkbookFactory.create(new File("data.xlsx")) or pass an InputStream if the file comes from a network or upload. This returns a Workbook object. Wrap the call in a try-with-resources block so the workbook is closed automatically.
  4. Select the sheet. Call workbook.getSheetAt(0) for the first sheet, or workbook.getSheet("Sheet1") by name. Check for null if the name might not exist.
  5. Loop over the rows. Use sheet.iterator() or a for loop from sheet.getFirstRowNum() to sheet.getLastRowNum(). Note that getLastRowNum() returns the zero-based index of the last row, not the count, so loop with <=.
  6. Loop over the cells in each row. For each row, iterate from row.getFirstCellNum() to row.getLastCellNum() (which is exclusive, unlike the row method). Skip null cells.
  7. Read each cell by type. Use cell.getCellType() and a switch: STRING → getStringCellValue(), NUMERIC → getNumericCellValue() (check DateUtil.isCellDateFormatted(cell) first if the column holds dates), BOOLEAN → getBooleanCellValue(), FORMULA → getCachedFormulaResultType() then read the cached value, and BLANK → skip or treat as empty. Avoid calling toString() on a cell and parsing the result; it is fragile.
  8. Handle numbers carefully. Excel stores all numbers as doubles. A cell showing "1" may return 1.0. If you need integers, cast or use DataFormatter to get the displayed string. DataFormatter is also useful when you want the value as the user sees it, including formatting.
  9. Close the workbook. With try-with-resources this happens automatically. Closing releases file handles, which matters on Windows where an open handle can block deletion or overwriting.
  10. Test with both formats. Run your code against a small .xlsx and, if you expect legacy files, a .xls. WorkbookFactory should handle both, but confirm your dependency set includes poi-ooxml for .xlsx.

Common Mistakes

  • Off-by-one on rows vs cells. getLastRowNum() is inclusive; getLastCellNum() is exclusive. Mixing them up skips the last row or throws an exception.
  • Forgetting poi-ooxml. With only poi on the classpath, .xlsx files fail with a "no suitable provider" style error.
  • Assuming every cell is a string. Numeric and date cells will throw IllegalStateException if you call getStringCellValue() on them.
  • Leaving workbooks open. Not closing them leaks memory and locks files.
  • Using XSSFWorkbook for huge files. The standard reader loads the whole sheet into memory; very large files can cause OutOfMemoryError.

Tips

  • Use the ss.usermodel interfaces rather than concrete HSSF/XSSF classes so the same code works for both formats.
  • Use DataFormatter when you need the value as displayed (currency, percentages, dates) rather than the raw double.
  • For read-only workloads, open with WorkbookFactory.create(file, null, true) to reduce memory use.
  • For very large .xlsx files, use the streaming SXSSFReader or the event API instead of loading the whole workbook.
  • Validate headers and expected column counts before processing data rows.

Troubleshooting

  • "Your InputStream was neither an OLE2 stream, nor an OOXML stream". The file is not a real Excel file, is corrupt, or is actually CSV/HTML renamed to .xlsx. Open it in Excel to confirm, or check the file's magic bytes.
  • ClassNotFoundException or NoClassDefFoundError for POI classes. Dependencies are missing or mismatched. Run your build tool's dependency tree and make sure poi and poi-ooxml are the same version.
  • OutOfMemoryError on large files. Switch to the streaming reader or increase heap only as a stopgap; streaming is the correct fix.
  • Dates come back as numbers. Check DateUtil.isCellDateFormatted(cell) and convert with cell.getDateCellValue().
  • File locked on Windows. A previous workbook was not closed. Ensure try-with-resources is used everywhere.

Frequently Asked Questions

Do I need Apache POI, or is there a built-in Java way?

Java has no built-in Excel reader. Apache POI is the standard choice. Alternatives include fastexcel and JExcelAPI for older .xls files, but POI covers both formats and is the most widely documented.

Can I read .xls and .xlsx with the same code?

Yes, if you use the ss.usermodel interfaces and WorkbookFactory. Include both poi and poi-ooxml dependencies.

How do I read a password-protected workbook?

Use WorkbookFactory.create(file, password) with the correct password. POI cannot open an encrypted file without it.

Why does my numeric cell return 1.0 instead of 1?

Excel stores all numbers as doubles. Format the value yourself, or use DataFormatter to get the displayed string.

Can I read only one sheet?

Yes. Call workbook.getSheetAt(index) or workbook.getSheet(name) and iterate only that sheet. The rest of the workbook is still loaded, so for very large files use the streaming reader.

Is POI safe to use in a server application?

Yes, but treat uploaded Excel files as untrusted input: limit file size, close workbooks promptly, and consider running parsing in a separate thread or process with memory limits to contain failures.