To read an Excel file in Java, use Apache POI: add the poi-ooxml dependency to your build, open the file with WorkbookFactory.create(...), loop over the sheets, rows and cells, and close the workbook when done. That one library handles both the modern .xlsx format and the older .xls format, which is why it is the default choice for most projects.
What You'll Need
- A Java project built with Maven or Gradle (a plain IDE project with manually added JARs also works, but dependency management is easier).
- A JDK installed and your build tool able to download dependencies from Maven Central.
- An Excel file to test with. Keep a small one with a few rows for early testing.
- Basic familiarity with collections and try-with-resources in Java.
Step-by-Step
- Add the dependency. For Maven, put this in your
pom.xml:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.5</version>
</dependency>
For Gradle, use implementation 'org.apache.poi:poi-ooxml:5.2.5'. Check Maven Central for the current stable version rather than copying an old one; version numbers change over time. The poi-ooxml artifact pulls in the base poi library and the OOXML schemas, so you do not need to add them separately.
- Import the classes you need. At minimum:
org.apache.poi.ss.usermodel.Workbook,WorkbookFactory,Sheet,Row,Cell, andorg.apache.poi.ss.usermodel.DataFormatterif you want display strings. - Open the workbook. Use a try-with-resources block so the file handle is closed automatically:
try (Workbook workbook = WorkbookFactory.create(new File("data.xlsx"))) {
// read here
}
WorkbookFactory.create inspects the file and returns an XSSFWorkbook for .xlsx or an HSSFWorkbook for .xls, so the same code works for both. If you know the format, you can also use new XSSFWorkbook(...) or new HSSFWorkbook(...) directly.
- Get the sheet you want. Either by index (
workbook.getSheetAt(0)) or by name (workbook.getSheet("Sheet1")). Check fornullwhen looking up by name. - Loop over the rows. Use
for (Row row : sheet)for a simple iteration, orsheet.getRow(i)with an index loop if you need to skip a header row or handle gaps. Note thatsheet.getLastRowNum()returns the zero-based index of the last row, not a count. - Read each cell according to its type. Do not call
getStringCellValue()on a numeric cell; it throwsIllegalStateException. Switch oncell.getCellType()and handleSTRING,NUMERIC,BOOLEAN,FORMULA,BLANKandERROR. For formula cells, usegetCachedFormulaResultType()to see what the formula evaluated to. - Handle dates and numbers. A date in Excel is a numeric cell with a date format. Check
DateUtil.isCellDateFormatted(cell)and callcell.getDateCellValue()if true; otherwise treat it as a number withgetNumericCellValue(). For display purposes,new DataFormatter().formatCellValue(cell)returns the string as Excel shows it, which is often the simplest option. - Close everything. The try-with-resources block closes the workbook. If you opened the file via an
InputStream, close that too. On Windows, leaving a workbook open locks the file.
Common Mistakes
- Using the wrong artifact.
poialone does not read.xlsx; you needpoi-ooxml. - Ignoring cell types. Assuming every cell is a string is the most common cause of runtime exceptions.
- Misreading
getLastRowNum(). It is an index, so a sheet with 10 rows returns 9. Iterating to<= getLastRowNum()is correct; using it as a count is not. - Forgetting to close the workbook. This leaks file handles and can lock the file.
- Expecting POI to evaluate formulas. POI reads the cached result stored in the file. If the file was never opened and saved by Excel, the cached value may be missing.
- Adding every POI sub-artifact manually. Dependency management handles transitive dependencies; adding JARs by hand often causes version conflicts.
Tips
- Use
DataFormatterwhen you just need the text a user sees; it handles number formats, dates and percentages without manual type checks. - For large files, use the streaming
SXSSFReaderorXSSFReaderAPIs instead of loading the whole workbook into memory. - Guard against null rows and null cells:
sheet.getRow(i)returnsnullfor empty rows, androw.getCell(j)returnsnullfor empty cells. - Read the header row first and map column names to indices so your code survives column reordering.
- Set a sensible cell-missing policy with
Row.MissingCellPolicy.RETURN_BLANK_AS_NULLif you prefer nulls over exceptions.
Troubleshooting
NoClassDefFoundErrororClassNotFoundExceptionfor POI classes: the dependency is not on the runtime classpath. Refresh your build and check the dependency tree for conflicts.InvalidFormatExceptionorOLE2NotOfficeXmlFileException: the file extension does not match the actual format, or the file is corrupted. Open it in Excel and re-save it.IllegalStateException: Cannot get a STRING value from a NUMERIC cell: you are calling the wrong getter for the cell type. Switch ongetCellType()first.- File locked or cannot be deleted after reading: a workbook or stream was not closed. Wrap it in try-with-resources.
- Empty or wrong values from formula cells: the workbook has no cached result. Open and save it in Excel, or evaluate with a formula evaluator.
- Out of memory on large files: switch to the streaming reader APIs and process rows as they arrive.
Frequently Asked Questions
Which library should I use to read Excel files in Java?
Apache POI is the most widely used and handles both .xlsx and .xls. Alternatives exist, but POI covers the common cases and is actively maintained.
Can Apache POI read both .xls and .xlsx files?
Yes. WorkbookFactory.create detects the format automatically and returns the right workbook implementation.
Do I need a different dependency for .xlsx?
Yes, use poi-ooxml for .xlsx. The base poi artifact alone only covers the older .xls format.
How do I read a date cell correctly?
Check DateUtil.isCellDateFormatted(cell) and use getDateCellValue(). Otherwise the value comes back as a serial number.
Does POI calculate formulas for me?
POI reads the cached result stored in the file. To recalculate, use a FormulaEvaluator from the workbook, but results can differ from Excel for complex functions.
Can I read a password-protected Excel file?
Yes, with the appropriate POI encryption support, but the exact API depends on the protection type. Check the POI documentation for the version you are using.