You can read an Excel file in Java by adding a library that understands the .xlsx format to your classpath and then iterating over the workbook's sheets, rows and cells. There is no Excel reader in the Java standard library, so plain Java alone cannot open a spreadsheet. Apache POI is the most widely used open-source option, and for most projects it is the safest choice. The steps below walk through setting up POI with Maven, reading both .xlsx and legacy .xls files, handling cell types correctly, closing resources, and dealing with the larger-file case where a normal in-memory read will run out of memory.
What You\'ll Need
- Java installed (version 8 or later is fine for current Apache POI releases; check the POI download page for the minimum supported version of the release you pick).
- A build tool such as Maven or Gradle, or the POI jars downloaded manually and placed on the classpath.
- A sample spreadsheet to test against, ideally with a header row plus a few data rows.
- An IDE or a plain text editor and a terminal, whichever you normally use.
- The Apache POI artifacts:
poifor the shared classes,poi-ooxmlfor .xlsx files, andpoi-ooxml-liteif you want a smaller set of the schema classes.
Step-by-Step
- Add the dependencies. If you use Maven, add
poiandpoi-ooxmlto yourpom.xml. The easiest way is to copy the current coordinates from the Apache POI download page rather than guessing a version. With Gradle, use the equivalentimplementationlines. If you are not using a build tool, download the binary distribution from the official Apache site and add every jar in itslibandooxml-libfolders to your classpath. Missing transitive jars are the most common cause of aNoClassDefFoundErrorat runtime, so always take the full set the distribution ships, not just the two main jars. - Create the workbook object. For .xlsx files use
XSSFWorkbook; for the older .xls format useHSSFWorkbook. Both live in theorg.apache.poi.xssf.usermodelandorg.apache.poi.hssf.usermodelpackages respectively. Open the file with aFileInputStreamor, for recent POI versions, by passing ajava.io.Filedirectly. The workbook holds everything in memory, which matters for the streaming section below. - Pick the sheet. Call
getSheetAt(0)for the first sheet, orgetSheet("Sheet1")to select by name. Iterate withgetNumberOfSheets()andgetSheetAt(i)if you need all of them. Sheet names are exactly as shown on the Excel tabs, including spaces. - Loop over the rows. Each sheet has a
getFirstRowNum()andgetLastRowNum(), and you iterate withgetRow(i). Important:getLastRowNum()returns the zero-based index of the last row, not a count, so a sheet with rows 0 to 4 returns 4. Also, it counts rows that exist but are entirely empty, and it can return a very large number for sheets that once had data further down and were cleared. Rather than looping to that number blindly, skip null rows with a check. - Loop over the cells, and read the type. For each row, get
getFirstCellNum()andgetLastCellNum()(this one is exclusive, and returns the count of cells, not an index). Every cell has agetCellType()value fromCellType:STRING,NUMERIC,BOOLEAN,FORMULA,BLANKorERROR. Switch on that value and call the matching getter:getStringCellValue(),getNumericCellValue(),getBooleanCellValue(). Never call a getter that does not match the type; it throws anIllegalStateException. - Handle dates and formulas. Dates are stored as numeric cells in Excel. Check
DateUtil.isCellDateFormatted(cell)and, if it returns true, readgetDateCellValue()to get ajava.util.Date; otherwise read the number. For formulas, readgetCachedFormulaResultType()and then either take the cached value or callgetNumericCellValue()on the result. If the file was saved by something that did not compute formulas, the cached value may be zero or blank. - Close everything in a finally block or try-with-resources. Workbooks hold file handles. Close the
Workbookand any streams you opened. In modern Java, try-with-resources is cleanest. On older codebases, close in afinallyso an exception in the middle of reading does not leak the handle. - Test against real data. Run your code against your sample sheet, printing each row's values. Then test a second file with mixed types (text, numbers, dates, blanks) and a third that is empty or has no header. Most production bugs appear in those edge cases, not in the happy path.
Common Mistakes
- Using HSSFWorkbook for .xlsx files. That combination throws
OfficeXmlFileException. UseXSSFWorkbookfor .xlsx andHSSFWorkbookfor .xls, or useWorkbookFactory.create(File), which detects the format automatically. - Missing POI jars on the classpath. The symptom is a
NoClassDefFoundErrorfor a POI or XMLBeans class. The fix is to include all jars from the distribution'slibandooxml-libfolders, or let Maven resolve the transitive dependencies. - Calling the wrong getter for a cell type. Reading a numeric cell with
getStringCellValue()gives anIllegalStateException. Always switch ongetCellType()first. - Forgetting that empty cells return null.
row.getCell(i)returns null when the cell has never been created, so dereferencing it throws aNullPointerException. Check for null before use, or usegetCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK)so a blank cell is returned instead of null. - Leaving the workbook open. On Windows, an unclosed file is locked and cannot be overwritten, and long-running code leaks handles until the process dies.
- Reading a huge sheet with
XSSFWorkbook. Memory use grows with the number of rows and columns, and large files can exhaust the heap. Use the streaming reader for big files.
Tips
- For large files, use
XSSFReaderor the event-basedXSSFSheetXMLHandler, which stream rows instead of loading the whole workbook. This is the right approach for anything that does not comfortably fit in memory. - Iterate cells with an explicit index from 0 to
getLastCellNum() - 1rather than relying on cell order, so you do not skip a blank cell or misalign columns. - Validate headers before reading data rather than assuming column positions. Do this and mismatches surface immediately instead of at row 400.
- Trim and normalise text when you convert to your own model objects; spreadsheet users often leave trailing spaces.
- Check for merged regions with
getNumMergedRegions()if layout matters. A merged cell only stores its value in the top-left cell; the others read as blank. - Prefer
WorkbookFactorywhen the file type is not known in advance. It picks the right implementation for you and reads password-protected files when supplied the password.
Troubleshooting
If the code will not compile, check the imports first: org.apache.poi.ss.usermodel.* contains the interfaces, while the concrete classes are in the hssf and xssf packages. If you get NoClassDefFoundError or ClassNotFoundException at runtime, your classpath is incomplete; add every jar in the distribution or let your build tool resolve transitively.
If you get OfficeXmlFileException, you are using the wrong workbook class for the file extension. If you get InvalidFormatException, the file is not a real spreadsheet (often it is an HTML or CSV file saved with an Excel extension, or a corrupt download) and you should open it in Excel to confirm. If NoSuchFileException or FileNotFoundException appears, check the path and whether the process is running from the directory you think it is.
If dates appear as odd numbers, you were reading a numeric cell without the date check. If formula results are zero or blank, the file was not recalculated before saving. If a large file throws OutOfMemoryError, switch to the streaming reader. If an EncryptedDocumentException is thrown, the file is password protected; pass the password to WorkbookFactory.create(File, String).
If it still will not work, open the file in Excel and save a copy as a fresh .xlsx. That clears many corruption problems, and if your code reads the fresh copy fine, the original file was the issue rather than your Java setup.
Frequently Asked Questions
Can I read Excel files with no external library at all?
No. The Java standard library has no Excel parser. You can read an .xlsx file as a ZIP archive and parse the XML inside by hand, since that is what an .xlsx file actually is, but it is complex and fragile. Use Apache POI or another maintained library instead.
Which library should I choose, POI or something lighter?
Apache POI is the most complete and widely documented option, and it handles both .xls and .xlsx. Lighter libraries exist for specific cases, often streaming or read-only. If you need full format support and are not constrained on size, POI is the safe default.
Do I need different code for .xls and .xlsx?
Mostly not. WorkbookFactory.create() detects the format and returns the right implementation, so your iteration code stays the same. Only if you instantiate the workbook class directly do you have to pick HSSFWorkbook or XSSFWorkbook.
Why do blank cells cause a NullPointerException?
Because getCell() returns null for a cell that was never created in the file. Guard with a null check or use MissingCellPolicy.CREATE_NULL_AS_BLANK to receive a blank cell instead.
How do I read only one row or one column?
Read the whole sheet's row range but filter inside the loop, or seek a single row with getRow(index) and read the cells you need. POI has no built-in column reader; a column is just index n across every row.
Is reading a large spreadsheet in memory safe?
Not reliably. Memory use grows with row and column count, so very large files can exhaust the heap. Use POI's event-based or streaming reader for those, which reads rows one at a time.