java.lang.OutOfMemoryError: Java heap space while reading excel with Apache POI

user467871 picture user467871 · May 20, 2011 · Viewed 45.3k times · Source

My file is 9MB and I got this error while loading workbook.

XSSFWorkbook workbook = new XSSFWorkbook(excelFilePath); 

this line causes to java.lang.OutOfMemoryError: Java heap space

How can I solve this?

Answer

Randomness picture Randomness · May 20, 2011

First thing to check - are you opening the XSSFWorkbook with an InputStream or a File? Opening it with a File is much lower memory.

Next up, do you want to read or write? If memory is very tight for you, there are alternate options for using XSSF in a sax like way.

For reading, see http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api for details of using XSSF + Sax. As another option, if you just want to get the textual content of the file, then it looks like Apache Tika has an event based text extractor for .xlsx files using POI.

For writing, there has been lots of discussions on the POI dev list recently about improving the "Big Grid Demo". You might want to follow those - http://poi.apache.org/mailinglists.html