To read large Excel files in Java without triggering an OutOfMemoryError, use the Apache POI library with the Event API (Streaming Reader) or the SXSSF implementation for writing. Standard DOM-based parsing loads the entire spreadsheet into RAM, which is unsustainable for files with hundreds of thousands of rows. By using a streaming approach, Java processes the file row-by-row, keeping the memory footprint constant regardless of the file size.
What You'll Need
- Java Development Kit (JDK) 8 or higher installed on your system.
- An Integrated Development Environment (IDE) such as IntelliJ IDEA, Eclipse, or VS Code.
- A build automation tool like Maven or Gradle to manage dependencies.
- The Apache POI library (specifically
poi-ooxml) added to your project dependencies. - A large
.xlsxfile for testing the streaming implementation.
Step-by-Step
- Configure Your Build File: Start by adding the necessary Apache POI dependencies to your project. If you are using Maven, add the
poi-ooxmldependency to yourpom.xml. Ensure you include the latest stable version to maintain compatibility with newer Excel formats. If using Gradle, add the implementation line to yourbuild.gradlefile. This provides the classes needed to handle the XML-based structure of.xlsxfiles. - Avoid the User Model (XSSFWorkbook): The most common mistake when dealing with large files is using
XSSFWorkbook workbook = new XSSFWorkbook(file). This method loads the entire document into a tree of Java objects. For a file with 100,000 rows, this can easily consume several gigabytes of heap space. Instead, you must use a streaming reader. While Apache POI provides a low-level Event API (XLSReader), it is complex to implement. A more practical approach is using a wrapper library likemonitorjbl/excel-streaming-readeror implementing the POIXSSFSheetin a way that minimizes object creation. - Implement the Streaming Reader: Initialize the streaming reader by passing the file path. The streaming reader works by reading the underlying XML stream of the Excel file and triggering events as it encounters rows and cells. This prevents the JVM from attempting to map the entire XML structure to memory. Create a
Workbookinstance using the streaming provider, which will act as a proxy that loads only a small window of rows into memory at any given time. - Iterate Through Sheets and Rows: Use a standard
for-eachloop to iterate through the sheets in the workbook. Once you have the desired sheet, iterate through the rows. Because the streaming reader discards rows after they have been processed, you cannot move backward in the file. You must process the data linearly. Inside the row loop, iterate through the cells using a loop from 0 to the last column index. - Handle Cell Types Dynamically: Excel cells can contain strings, numbers, booleans, or formulas. To avoid
IllegalStateException, use aswitchstatement or a series ofif-elseblocks checkingcell.getCellType(). For numeric cells, usecell.getNumericCellValue(); for text, usecell.getStringCellValue(). If you encounter a formula, you can either read the formula string or use aFormulaEvaluatorto get the cached result of the calculation. - Map Data to POJOs: To make the data usable in your application, map each row to a Plain Old Java Object (POJO). Create a class that represents a single record in your spreadsheet. As you iterate through the cells of a row, assign the values to the fields of your POJO. This allows you to pass the data to a database or a processing engine without keeping the raw Excel cell objects in memory.
- Close Resources Properly: Excel files are system resources. Wrap your workbook and file input streams in a
try-with-resourcesblock. This ensures that the file handle is released even if an exception occurs during the reading process. Failing to close the workbook can lead to file locks and memory leaks in long-running server applications.
Common Mistakes
The most frequent error is using XSSFWorkbook for files larger than 10MB. While it works for small files, it scales poorly. Another mistake is attempting to access cells out of order. Streaming readers are forward-only; if you try to access row 5 after you have already moved to row 10, the library will either throw an exception or be forced to re-read the file from the beginning, destroying the performance gains of streaming.
Developers also often forget to handle merged cells. In a streaming environment, only the first cell of a merged region typically contains the value. The other cells in the merged range will appear as null or empty. If your data relies on merged cells, you must implement a tracking mechanism to remember the last known value of a merged region as you move across the row.
Another common pitfall is ignoring the DataFormatter class. Using cell.getStringCellValue() on a numeric cell will throw an exception. Many developers try to manually convert numbers to strings, but DataFormatter is the official way to get the value exactly as it appears in the Excel UI, including currency symbols and date formatting.
Tips
To further optimize performance, increase the JVM heap size using the -Xmx flag (e.g., -Xmx2g). While streaming reduces memory usage, the processing of millions of cells still creates many short-lived objects that can trigger frequent Garbage Collection (GC) pauses. Increasing the heap gives the GC more breathing room.
If you are reading the file only to move the data into a database, avoid loading the entire list of POJOs into a Java List. Instead, use batch inserts. Process 1,000 rows, write them to the database, and then clear your local list. This prevents the application from running out of memory even if the streaming reader is working perfectly.
For extremely large files, consider converting the Excel file to CSV using an external tool or a script before processing it in Java. CSV files are inherently streamable and require significantly less overhead than the zipped XML structure of .xlsx files.
Troubleshooting
If you encounter a java.lang.OutOfMemoryError: Java heap space, first verify that you are not using XSSFWorkbook. If you are using a streaming reader and still seeing this error, check if you are storing all the read rows in a List or Map. The memory leak is likely in your data storage, not the reading process. Clear your collections periodically.
If you see a NullPointerException when accessing cells, remember that Apache POI does not create cell objects for empty cells. Always check if the cell is null using if (cell == null) before calling getCellType(). You may also want to use row.getCell(index, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK) to ensure a cell object is always returned.
If the application hangs or becomes extremely slow, check for "volatile" formulas in the spreadsheet. Some formulas recalculate every time the file is opened. If your code is attempting to evaluate these formulas using a FormulaEvaluator, it can lead to massive performance degradation. Try reading the cached value instead of re-evaluating the formula.
Frequently Asked Questions
Can I use the same method for .xls and .xlsx files?
No. .xls files (Excel 97-2003) use a binary format (HSSF), while .xlsx files use an XML-based format (XSSF). You will need to use HSSF classes for the former and XSSF or SXSSF for the latter.
Is there a limit to how many rows a streaming reader can handle?
The streaming reader is limited by the maximum row limit of Excel itself (1,048,576 rows per sheet). As long as you process rows linearly and do not store them all in memory, the Java application can handle files of any size.
Does streaming reading affect the speed of data retrieval?
Streaming is generally faster for large files because it avoids the massive overhead of building a DOM tree. However, for very small files, the difference is negligible, and the standard User Model may be slightly easier to implement.
How do I handle dates in large Excel files?
Excel stores dates as numbers. Use DateUtil.isCellDateFormatted(cell) to check if a numeric cell represents a date, then use cell.getDateCellValue() to retrieve it as a Java Date object.
Can I modify a large file while reading it using a stream?
No. Streaming readers are read-only. To modify a large file, you should read the original file using a streaming reader and write the modified data to a new file using SXSSFWorkbook, which is the streaming version of the workbook writer.