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:
poifor the older .xls format andpoi-ooxmlfor .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
WorkbookFactoryhandles both. - An IDE or text editor. Any will do.
Step-by-Step
- Add the dependencies. In Maven, add
org.apache.poi:poiandorg.apache.poi:poi-ooxmlto yourpom.xml. In Gradle, add the same coordinates to yourbuild.gradle. Use the latest stable versions shown on Maven Central; exact version numbers change, so check there rather than copying an old one. - Import the classes you need. At minimum:
org.apache.poi.ss.usermodel.Workbook,WorkbookFactory,Sheet,Row, andCell. These interfaces work for both .xls and .xlsx, which keeps your code format-agnostic. - Open the file. Use
WorkbookFactory.create(new File("data.xlsx"))or pass anInputStreamif the file comes from a network or upload. This returns aWorkbookobject. Wrap the call in a try-with-resources block so the workbook is closed automatically. - Select the sheet. Call
workbook.getSheetAt(0)for the first sheet, orworkbook.getSheet("Sheet1")by name. Check fornullif the name might not exist. - Loop over the rows. Use
sheet.iterator()or a for loop fromsheet.getFirstRowNum()tosheet.getLastRowNum(). Note thatgetLastRowNum()returns the zero-based index of the last row, not the count, so loop with<=. - Loop over the cells in each row. For each row, iterate from
row.getFirstCellNum()torow.getLastCellNum()(which is exclusive, unlike the row method). Skip null cells. - Read each cell by type. Use
cell.getCellType()and a switch:STRING→getStringCellValue(),NUMERIC→getNumericCellValue()(checkDateUtil.isCellDateFormatted(cell)first if the column holds dates),BOOLEAN→getBooleanCellValue(),FORMULA→getCachedFormulaResultType()then read the cached value, andBLANK→ skip or treat as empty. Avoid callingtoString()on a cell and parsing the result; it is fragile. - Handle numbers carefully. Excel stores all numbers as doubles. A cell showing "1" may return
1.0. If you need integers, cast or useDataFormatterto get the displayed string.DataFormatteris also useful when you want the value as the user sees it, including formatting. - 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.
- Test with both formats. Run your code against a small .xlsx and, if you expect legacy files, a .xls.
WorkbookFactoryshould handle both, but confirm your dependency set includespoi-ooxmlfor .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 onlypoion the classpath, .xlsx files fail with a "no suitable provider" style error. - Assuming every cell is a string. Numeric and date cells will throw
IllegalStateExceptionif you callgetStringCellValue()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.usermodelinterfaces rather than concreteHSSF/XSSFclasses so the same code works for both formats. - Use
DataFormatterwhen 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
SXSSFReaderor 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
poiandpoi-ooxmlare 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 withcell.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.