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:poi and org.apache.poi:poi-ooxml. For Gradle, add the same two coordinates to your dependencies block.
  • 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/resources folder or an absolute path such as C:/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

  1. Create the project and add the dependency. In Maven, add both POI artifacts to your pom.xml and 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 the poi-ooxml artifact and only add poi, .xlsx files will fail with a "no ooxml" style error because the XML-based format lives in the second jar.
  2. Place the Excel file. Either put it in src/main/resources and load it from the classpath, or reference it by absolute path. When you use a classpath resource inside a packaged jar, read it as an InputStream rather than a File, because a File handle cannot point inside a jar.
  3. Open the workbook. The most robust way is WorkbookFactory.create(inputStream), which detects the format from the file and returns either an XSSFWorkbook or an HSSFWorkbook. Use it inside a try-with-resources block so the workbook is closed and file handles released even if an exception occurs.
  4. Select the sheet. Get it by index with workbook.getSheetAt(0) for the first sheet, or by name with workbook.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.
  5. Find the last row and column. Use sheet.getLastRowNum() for the last row index and row.getLastCellNum() for the last cell index of a given row. Both are zero-based indexes, and getLastCellNum() actually returns a count, not an index, so loop with for (int c = 0; c < row.getLastCellNum(); c++).
  6. Loop the rows and skip blanks. Iterate from 0 (or sheet.getFirstRowNum()) to getLastRowNum(). Inside the loop, call sheet.getRow(r) and check for null, because entirely empty rows in the middle of a sheet return null rather than an empty row object.
  7. 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 check cell.getCellType() and branch: STRING uses getStringCellValue(), NUMERIC uses getNumericCellValue(), BOOLEAN uses getBooleanCellValue(), FORMULA uses getCachedFormulaResultType() and then the matching getter, and BLANK yields an empty string.
  8. 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 with Double.parseDouble later if you need numbers.
  9. 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. Check DateUtil.isCellDateFormatted(cell) and, if true, call cell.getLocalDateTimeCellValue() (or getDateCellValue() for the older java.util.Date) to get a real date.
  10. 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 a main method:
    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();
        }
    }
  11. 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 poi and not poi-ooxml, which breaks every .xlsx read.
  • 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 an IllegalStateException.
  • 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.234E9 or a lost leading zero. Use DataFormatter or 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 .xlsx files, POI's XSSFWorkbook loads everything into memory. The SAX-based event API (XSSFReader) or SXSSFWorkbook for 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 BigDecimal for 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.