Quick revision
The short answer
We replace XSSFWorkbook with new SXSSFWorkbook(100), which keeps only the last 100 rows in memory and flushes older rows to temporary files, so memory stays flat for any number of rows. Rows must be written in order, because flushed rows can no longer be read or changed. When we finish, we write the workbook and make sure the temporary files are deleted with dispose() (or close() in newer POI versions, check yours), optionally compress the temp files, and avoid autoSizeColumn over all rows.
What to remember
In this answer, we replaced XSSFWorkbook with SXSSFWorkbook to write 500,000 rows with flat memory. The row window keeps only the last 100 rows in memory and flushes the rest to temp files, so rows must be written in order. We closed the workbook and called dispose() in a finally block so temp files are deleted even after failures, compressed the temp files to save disk, and used fixed column widths because autoSizeColumn only sees tracked columns in a streaming sheet.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We replace XSSFWorkbook with new SXSSFWorkbook(100), which keeps only the last 100 rows in memory and flushes older rows to temporary files, so memory stays flat for any number of rows. Rows must be written in order, because flushed rows can no longer be read or changed. When we finish, we write the workbook and make sure the temporary files are deleted with dispose() (or close() in newer POI versions, check yours), optionally compress the temp files, and avoid autoSizeColumn over all rows.
Why this question is asked
Writing half a million rows to Excel is a normal request in reporting services, and it is the point where the usual POI code stops working. The code is correct, the export works in tests with 1,000 rows, and in production it fails with OutOfMemoryError. Interviewers ask this because the fix is simple to write but has several settings and traps that matter in production. In this answer, we will see why XSSFWorkbook runs out of memory, rewrite the export with SXSSFWorkbook, understand the row window and its rule about order, clean up the temporary files properly, and finish with temp file compression and column sizing.
1Why XSSFWorkbook Runs Out of Memory
XSSFWorkbook builds the entire workbook as objects in memory: every row is an object, every cell is an object, and each one holds its value, style and a piece of the XML structure. Only when we call write() does POI turn the objects into XML and zip them. For 500,000 rows with 10 columns, that is 5 million cell objects, and a heap of a few gigabytes is easily not enough.
Notice that memory grows with every row, and nothing is released until the end. The fix is to stop keeping old rows in memory at all.
2Rewriting the Export With SXSSFWorkbook
SXSSFWorkbook, the streaming version of XSSF, has the same Workbook, Sheet, Row and Cell interfaces, so most of our code stays the same. The constructor argument is the row access window: how many rows stay in memory. When we create row 101, POI writes row 1 as XML to a temporary file on disk and drops it from memory.
9 messages in order. Play them, or step through them one at a time.
Only the window lives in memory; everything older is on disk until write().
Notice the try (wb; ...) form, available since Java 9, which closes a variable declared before the try. We declare the workbook outside so that the finally block can still reach it. The finally block runs after the resources are closed, and it runs whether write() succeeded or threw.
3Writing Rows in Order
The window has a strict consequence: once a row has been flushed, it is gone from memory, and we cannot read it or change it again. sheet.getRow(5) returns null when row 5 has already been flushed, and trying to create a row with an index inside the flushed range fails.
So the export must be written top to bottom, in one pass. Things we used to do afterwards must be planned before: a totals row at the top needs to be computed first or moved to the bottom as a SUM formula, and a header must be written first. If we really need random access to recent rows, a larger window helps, and new SXSSFWorkbook(-1) turns automatic flushing off so we can call sheet.flushRows(n) ourselves.
4Cleaning Up the Temporary Files
The temporary files live in java.io.tmpdir, typically /tmp, and each sheet has one. For a 500,000-row export they can be hundreds of megabytes before compression. They must be deleted when we are done, and especially when the export fails half way, or a busy service fills its disk within days.
Historically, closing the workbook did not delete them and we had to call wb.dispose(). Newer POI versions have changed how close() and dispose() relate, so check your version's documentation; calling dispose() in a finally block is safe and makes the intent obvious in either case. In containers, also check where java.io.tmpdir points: if /tmp is a memory-backed volume, the temp files consume memory, which defeats the point of streaming.
5Compressing Temp Files and Sizing Columns
setCompressTempFiles(true) gzips each temp file as it is written. Sheet XML is very repetitive, so it shrinks a lot, often to a small fraction of its size, at the cost of some CPU to compress and decompress. On servers with small or shared disks it is usually worth it.
Column sizing needs care. autoSizeColumn measures the cells it can see, and with SXSSF it can only see the window, not the rows already on disk. POI makes this explicit: to auto-size, we must call sheet.trackAllColumnsForAutoSizing() (or trackColumnForAutoSizing(i)) before writing rows, so POI records the widest value as rows pass through. Tracking costs time on every cell, so for very large exports fixed widths with setColumnWidth are simpler and faster, which is what the example above does.
| Setting | What it does | Cost |
|---|---|---|
new SXSSFWorkbook(100) | Keeps 100 rows in memory | Older rows cannot be accessed |
setCompressTempFiles(true) | Gzips temp files | CPU for compression |
dispose() in finally | Deletes temp files | None; always do it |
trackAllColumnsForAutoSizing() | Lets autoSizeColumn see all rows | Slower writing |
setColumnWidth(i, w) | Fixed widths | Widths may not fit perfectly |
6Follow-up questions
What window size should we choose?
The default of 100 is fine for most exports. A larger window only helps if we need to go back to recent rows, and it costs memory per row. The real memory cost of an export usually comes from elsewhere, such as loading all the data from the database, so we stream the source as well.
Does SXSSF help with shared strings?
By default SXSSF writes text as inline strings in each cell instead of a shared strings table, which keeps memory flat. There is a constructor option to use a shared strings table, which makes files smaller when the same text repeats, but the table is held in memory, so for huge exports inline strings are safer.
Can we read an existing file with SXSSF?
No. SXSSF is only for writing. We can create an SXSSFWorkbook from an existing XSSFWorkbook to append rows to a template, but for reading large files we use the event API or a streaming reader library.
7Conclusion
In this answer, we replaced XSSFWorkbook with SXSSFWorkbook to write 500,000 rows with flat memory. The row window keeps only the last 100 rows in memory and flushes the rest to temp files, so rows must be written in order. We closed the workbook and called dispose() in a finally block so temp files are deleted even after failures, compressed the temp files to save disk, and used fixed column widths because autoSizeColumn only sees tracked columns in a streaming sheet.
Open with
XSSFWorkbook keeps every row and cell as objects until write, so 500,000 rows exhaust the heap. I would switch to SXSSFWorkbook with a window of 100: it has the same interfaces, keeps only the last hundred rows in memory, and flushes older rows as XML to temporary files, so memory stays flat.
Then, if they want more
The trade-off is that rows must be written in order; a flushed row returns null from getRow and can't be changed, so headers and totals have to be planned before or after the data. I'd call setCompressTempFiles(true) to gzip the temp files at some CPU cost, which helps on small disks.
Cleanup matters: I declare the workbook before the try, use it as a resource, and call dispose in a finally block so temp files in java.io.tmpdir are deleted even when the export fails; newer POI versions changed how close and dispose interact, so I'd check the version, but dispose in finally is always safe.
I'd also check that tmpdir is on a real disk in containers. Finally I'd avoid autoSizeColumn; with SXSSF it only works on tracked columns, so I use trackAllColumnsForAutoSizing before writing or, better for large files, fixed widths. And I create styles once.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9
- 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 "Writing 500,000 rows with XSSFWorkbook runs out of memory. Rewrite it with SXSSFWorkbook...": https://scrivio-interview-library.netlify.app/java/document-libraries/4112bbd004/