To read data from Excel in Java, add the Apache POI library to your project (or use its lighter sibling, SXSSF, for very large files), open the workbook with a WorkbookFactory or XSSFWorkbook, loop over the rows and cells of a sheet, and read each cell with a type-aware getter such as getStringCellValue() or getNumericCellValue(). The short version: three classes, Workbook, Sheet and Row, do most of the work, and DataFormatter handles the awkward business of turning any cell into a sensible string. The steps below walk through a complete, runnable example.
What You'll Need
- A Java development kit (JDK 8 or newer) and a build tool such as Maven or Gradle.
- The Apache POI dependency. For Maven, add
org.apache.poi:poiandorg.apache.poi:poi-ooxml. For Gradle, add the same two coordinates to yourdependenciesblock. - An Excel file saved as
.xlsx(Excel 2007 and later, handled by POI's XSSF implementation) or.xls(the older HSSF format). Modern POI handles both through the same interfaces. - Your IDE or editor of choice, and the file placed in a location your program can find, such as a
src/main/resourcesfolder or an absolute path such asC:/data/report.xlsx.
Dependency versions differ between releases, so check the current version listed for POI on Maven Central rather than copying a number from an old tutorial. Labels, package paths and class names are stable across versions; the exact version string is not.
Step-by-Step
- Create the project and add the dependency. In Maven, add both POI artifacts to your
pom.xmland run a build so your IDE downloads the jars and their transitive dependencies (commons-io, commons-compress, log4j-api and so on). If you skip thepoi-ooxmlartifact and only addpoi,.xlsxfiles will fail with a "no ooxml" style error because the XML-based format lives in the second jar. - Place the Excel file. Either put it in
src/main/resourcesand load it from the classpath, or reference it by absolute path. When you use a classpath resource inside a packaged jar, read it as anInputStreamrather than aFile, because aFilehandle cannot point inside a jar. - Open the workbook. The most robust way is
WorkbookFactory.create(inputStream), which detects the format from the file and returns either anXSSFWorkbookor anHSSFWorkbook. Use it inside a try-with-resources block so the workbook is closed and file handles released even if an exception occurs. - Select the sheet. Get it by index with
workbook.getSheetAt(0)for the first sheet, or by name withworkbook.getSheet("Sheet1"). Guard against a null result: a typo in the name returns null, not an exception, and the null only blows up on the next line. - Find the last row and column. Use
sheet.getLastRowNum()for the last row index androw.getLastCellNum()for the last cell index of a given row. Both are zero-based indexes, andgetLastCellNum()actually returns a count, not an index, so loop withfor (int c = 0; c < row.getLastCellNum(); c++). - Loop the rows and skip blanks. Iterate from
0(orsheet.getFirstRowNum()) togetLastRowNum(). Inside the loop, callsheet.getRow(r)and check for null, because entirely empty rows in the middle of a sheet return null rather than an empty row object. - Read each cell by type. Get the cell with
row.getCell(c, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL)so missing cells do not throw. Then checkcell.getCellType()and branch:STRINGusesgetStringCellValue(),NUMERICusesgetNumericCellValue(),BOOLEANusesgetBooleanCellValue(),FORMULAusesgetCachedFormulaResultType()and then the matching getter, andBLANKyields an empty string. - Or use DataFormatter instead. If you mainly want display strings,
new DataFormatter().formatCellValue(cell)returns exactly what Excel shows, including dates, percentages and currency formatting. This removes most type branching but gives you text, so convert withDouble.parseDoublelater if you need numbers. - Handle dates explicitly. A date cell is a numeric cell under the hood, so
getNumericCellValue()returns a serial number like 45000 rather than a date. CheckDateUtil.isCellDateFormatted(cell)and, if true, callcell.getLocalDateTimeCellValue()(orgetDateCellValue()for the olderjava.util.Date) to get a real date. - Print or store the data. Add each row to a
List<List<String>>, a list of your own POJO, or just print it with delimiters. Close the workbook when done. A complete minimal example inside amainmethod:try (InputStream in = Files.newInputStream(Paths.get("data.xlsx")); Workbook wb = WorkbookFactory.create(in)) { Sheet sheet = wb.getSheetAt(0); DataFormatter fmt = new DataFormatter(); for (int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++) { Row row = sheet.getRow(r); if (row == null) continue; for (int c = 0; c < row.getLastCellNum(); c++) { Cell cell = row.getCell(c, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL); System.out.print((cell == null ? "" : fmt.formatCellValue(cell)) + " | "); } System.out.println(); } } - Test with a messy file. Run it against a sheet with a header row, empty rows, a date column, a percentage column and a formula column to confirm each branch behaves. Only then move on to mapping rows into your domain objects.
Common Mistakes
- Adding only
poiand notpoi-ooxml, which breaks every.xlsxread. - Forgetting to close the workbook, which leaks file handles and can lock the file on Windows.
- Assuming row 0 is data: it is usually the header. Skip it or read it separately.
- Calling
getStringCellValue()on a numeric or formula cell, which throws anIllegalStateException. - Treating
getLastRowNum()as a row count. It is the last zero-based index, and a sheet with rows 0 to 9 reports 9, not 10. - Reading a numeric ID such as a phone number or zip code as a double and getting
1.234E9or a lost leading zero. UseDataFormatteror read it as a string where leading zeros matter. - Iterating with an enhanced for-loop over the sheet when rows are sparse; indexes are safer.
- Attempting to read a password-protected workbook without the password, which throws an
EncryptedDocumentException.
Tips
- For very large
.xlsxfiles, POI'sXSSFWorkbookloads everything into memory. The SAX-based event API (XSSFReader) orSXSSFWorkbookfor writing keeps memory manageable. The streaming reader pattern reads row by row and never holds the whole file. - Write cell-reading logic once in a helper method and reuse it; the type-branching code in every loop is how bugs creep in.
- Normalise values on import (trim strings, parse numbers with
BigDecimalfor money) instead of storing raw display text. - Log the row number when parsing fails so you can find the offending line in the spreadsheet immediately.
- If your source is a simpler CSV or the user can export it, CSV parsing is far lighter than a full POI dependency.
Troubleshooting
"Cannot get a STRING value from a NUMERIC cell": your code assumed a type. Switch to DataFormatter or branch on getCellType().
NoClassDefFoundError or ClassNotFoundException for POI classes: the dependency is missing or a transitive jar is excluded. Force a rebuild, check your dependency tree, and confirm both POI artifacts are present.
File not found: verify the relative path is relative to the working directory, not the source folder. Log new File(path).getAbsolutePath() to see where the program is actually looking.
Dates come out as numbers: you hit the numeric serial number. Use DateUtil.isCellDateFormatted() and the date getter.
EncryptedDocumentException: the file has a password; supply it or ask the owner for an unprotected copy.
Wrong or missing rows: check getFirstRowNum() and whether the file is a hidden or very distant getLastRowNum(), which can happen after heavy editing; a stray formatted row can inflate the last index.
Frequently Asked Questions
Do I need Apache POI, or is there something built into Java?
Java has no built-in Excel reader. POI is the most widely used free library. Alternatives exist, such as the commercial Aspose cells product, but POI is the standard open-source choice.
Can POI read both .xls and .xlsx files?
Yes. WorkbookFactory detects the format and returns HSSFWorkbook for .xls and XSSFWorkbook for .xlsx. You write code against the shared interfaces.
How do I read a specific cell, say B3?
Use sheet.getRow(2) and row.getCell(1). POI indexes are zero-based, so B3 is row index 2, column index 1.
How do I handle formulas?
Call cell.getCachedFormulaResultType() and read using the matching getter. POI returns the last value Excel calculated, not a fresh computation.
Can I read an Excel file that a user opens in Excel at the same time?
On Windows, an open file may be locked. Copy it first or ensure the user closes it. Reading the stream into memory first avoids the lock.
Does reading an Excel file require Excel to be installed?
No. POI reads the file format directly, so it runs on any machine, including Linux servers.