Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

How do you read a very large .xlsx file without loading it into memory? Compare POI's event API (XSSFReader with a SAX handler) with libraries such as excel-streaming-reader or FastExcel.

XSSFWorkbook loads the whole workbook into memory, often many times the file size, so for very large files we read the XML as a stream instead. POI's event API opens the package with OPCPackage, gets the sheet XML streams and the shared strings table from XSSFReader, and parses each sheet with SAX through XSSFSheetXMLHandler, which calls our handler once per cell. Libraries such as excel-streaming-reader and FastExcel wrap the same idea in a simple row iterator. Either way we get cached formula results, not fresh calculations.

Why this question is asked

Writing large Excel files has a well-known answer in SXSSF. Reading them is less obvious, because the ordinary POI API, the one every tutorial shows, needs the whole file in memory before we can read the first cell. When a partner sends a 200 MB workbook, a service with a 2 GB heap can fail before importing a single row. Interviewers ask this question to see whether we understand what is inside an .xlsx and how streaming parsers work. In this answer, we will see why the usual API uses so much memory, walk through POI's event API step by step, deal with large shared strings tables, compare it with wrapper libraries, and look at the limits around formulas.

1Why XSSFWorkbook Needs So Much Memory

An .xlsx file is a ZIP archive of XML parts: one per sheet, one for shared strings, one for styles, and a few more. The XML is highly compressible, so a 50 MB file can contain several hundred megabytes of XML. XSSFWorkbook unzips all of it, parses it into an XML object tree, and then builds POI's own row and cell objects on top. Every cell becomes several objects.

So the memory needed is many times the file size, and it is all needed at once, because XSSFWorkbook builds the complete model before returning. There is no way to tune this away: for large files we must avoid building the model at all.

2A Quick Recap of SAX Parsing

There are two main ways to read XML. A DOM parser reads the whole document into a tree of objects, which is easy to navigate but needs memory proportional to the document. A SAX parser reads the document as a stream and calls methods on our handler for each event: an element starts, some text appears, an element ends. It keeps almost nothing in memory, but we see each piece once, in order, and have to remember any state ourselves.

In a sheet's XML, each row is a <row> element and each cell a <c> element with a reference such as B7 and a value. For text, the value is usually not the text itself but an index into the shared strings table, a separate part that stores each distinct string once. That detail matters for memory, as we will see.

3Reading With POI's Event API

POI's event API gives us the pieces to parse sheets with SAX. OPCPackage opens the ZIP container, XSSFReader finds the parts, and XSSFSheetXMLHandler turns raw SAX events into simple callbacks for rows and cells, already formatted as text with the styles and DataFormatter.

Java
class RowCollector implements XSSFSheetXMLHandler.SheetContentsHandler {
private final List<String> current = new ArrayList<>();
public void startRow(int rowNum) { current.clear(); }
public void cell(String ref, String value, XSSFComment comment) { current.add(value); } // "B7", "1250.00"
public void endRow(int rowNum) { importer.accept(rowNum, List.copyOf(current)); } // one row at a time
}
try (OPCPackage pkg = OPCPackage.open(file.toFile(), PackageAccess.READ)) {
XSSFReader reader = new XSSFReader(pkg);
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(pkg);
StylesTable styles = reader.getStylesTable();
XSSFReader.SheetIterator sheets = (XSSFReader.SheetIterator) reader.getSheetsData();
while (sheets.hasNext()) {
try (InputStream sheet = sheets.next()) {
XMLReader parser = XMLHelper.newXMLReader(); // POI's hardened SAX parser
parser.setContentHandler(new XSSFSheetXMLHandler(
styles, null, strings, new RowCollector(), new DataFormatter(), false));
parser.parse(new InputSource(sheet)); // calls startRow, cell, endRow
}
}
}
Step throughEvent API reading one sheet
Our codeXSSFReaderSAX parserSheet handler
open package, get sheet streams
shared strings, styles, sheet XML
parse(sheet XML)
startRow(6)
cell("A7", "INV-104")
cell("B7", "1250.00")
endRow(6): hand the row on
... next row ...

8 messages in order. Play them, or step through them one at a time.

Rows flow through the handler one at a time; nothing builds a full model.

Notice how little stays in memory: one row in our collector, the styles table, and the shared strings. Our handler receives each row in order and must hand it on immediately, for example to a batch insert. Notice also that cell() is not called for empty cells, so a real handler uses the cell reference (B7 means column index 1) to put each value in the right column. Class and method names have moved between POI versions (XMLHelper replaced an older SAXHelper, for example), so check them against your version.

4When the Shared Strings Table Is the Problem

Streaming the sheet XML solves most of the memory problem, but not all of it. The cells refer to strings by index, so to turn index 48,213 into text the reader must be able to look up any string at any time. ReadOnlySharedStringsTable keeps the whole table in memory as a list of strings, which is far lighter than POI's full model but can still be large: a sheet of 2 million rows with a unique description in every row has 2 million shared strings.

For such files, there are temp-file backed shared strings tables that keep the strings on disk with an index and a small cache in memory. The excel-streaming-reader project, for example, offers options to store shared strings in a temporary file. It is slower to look up, but memory stays bounded whatever the file contains.

5Wrapper Libraries: Simpler Code on the Same Idea

The event API is powerful but low level: we write a handler, track columns by cell reference and manage state ourselves. Wrapper libraries hide that behind an ordinary iterator. excel-streaming-reader gives us a Workbook-like object whose sheets we can iterate row by row, using POI's types, while it streams underneath. FastExcel's reader module offers its own small API, a stream of rows from a sheet, and is designed for speed and low memory.

Java
// excel-streaming-reader (com.github.pjfanning)
try (Workbook wb = StreamingReader.builder().rowCacheSize(100).bufferSize(4096).open(in)) {
for (Row row : wb.getSheetAt(0)) {
String id = row.getCell(0).getStringCellValue(); // works for streamed rows
}
}
// FastExcel reader (org.dhatim)
try (ReadableWorkbook wb = new ReadableWorkbook(in)) {
wb.getFirstSheet().openStream().forEach(row -> importer.accept(row.getCellText(0)));
}
Ways to read a large .xlsx
ApproachMemoryEaseNotes
XSSFWorkbookMany times the file sizeEasiestRandom access, formula evaluation
POI event API (XSSFReader + SAX)Row at a time, plus shared stringsLow levelNo extra dependency, full control
excel-streaming-readerRow cache, optional temp-file stringsIterator of POI rowsForward only
FastExcel readerRow at a timeSmall stream APIForward only, fast

The cost of the convenience is control and some features: these libraries are forward-only like the event API, support a subset of what POI's full model offers, and are maintained by smaller communities, so we check their activity and version compatibility with POI. For most import jobs, a wrapper library is the pragmatic choice; the raw event API is for cases where we need full control, or want no extra dependency.

6What Streaming Cannot Do: Formulas

A formula evaluator needs to look at any cell the formula refers to, possibly on another sheet, at any time. A streaming reader has already forgotten those cells. So streaming readers give us the cached results: the values Excel calculated and stored in the file when it was last saved. For files saved by Excel this is usually exactly what we want.

The catch is files generated by other programs that write formulas without cached values. Then a streaming reader returns an empty value or the formula text for those cells. If we must have calculated values from such files, we either ask the producer to calculate before saving, or load that file with the full model and accept the memory cost, which makes it worth checking file sizes first.

7Follow-up questions

How does the event API handle dates?

XSSFSheetXMLHandler uses the styles table and the DataFormatter we pass to it, so a date cell arrives already formatted as text according to its format, such as 3/1/26. For reliable parsing we either pass a DataFormatter with a fixed locale and parse the text, or use the option that gives us raw values and convert the Excel date number ourselves with DateUtil.

Can we read only the first few rows of a huge file?

Yes, and streaming makes it cheap. The handler can throw a special exception, or the wrapper iterator can simply stop, after the rows we need, such as reading the header and ten sample rows for a preview. The full model would have to load the whole file first.

Does the event API protect against zip bombs?

It uses the same package code, so POI's ZipSecureFile checks on the inflate ratio and entry size still apply, and its XML parser is hardened against external entities. Streaming also limits the memory a malicious file can make us use.

8Conclusion

In this answer, we saw that XSSFWorkbook builds a full model in memory, often many times the file size. POI's event API avoids that: OPCPackage opens the file, XSSFReader provides the sheet streams, styles and shared strings, and a SAX parser with XSSFSheetXMLHandler calls our handler for each row and cell. Large shared strings tables can need a read-only or temp-file backed table. Wrapper libraries such as excel-streaming-reader and FastExcel give a simpler row iterator on the same idea, and all streaming readers return cached formula results rather than evaluating formulas.

What to say in the interviewAbout 80 seconds aloud

Open with

XSSFWorkbook parses the whole file into a DOM-like model with objects for every cell, so it often needs many times the file size in memory. For very large files I'd stream.

Then, if they want more

With POI's event API, I open the file with OPCPackage in read mode, create an XSSFReader to get the styles table, the sheet XML streams and the shared strings, and parse each sheet with a SAX parser using XSSFSheetXMLHandler.

That handler calls my SheetContentsHandler with startRow, cell and endRow, already formatted, so I can pass each row to a batch insert and keep almost nothing in memory. I have to track columns from the cell reference, because empty cells are not reported.

The remaining memory is the shared strings table; ReadOnlySharedStringsTable is light, but for files with millions of unique strings a temp-file backed table, like the option in excel-streaming-reader, keeps memory bounded. For most imports I'd actually use a wrapper such as excel-streaming-reader or FastExcel's reader, which give a forward-only row iterator on the same principle with much simpler code.

The limit of all streaming approaches is formulas: I only get the cached results Excel stored, not a fresh evaluation.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How do you read a very large .xlsx file without loading it into memory? Compare POI's...": https://scrivio-interview-library.netlify.app/java/document-libraries/7f21e7219c/