Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API to write huge excel files using java

I am looking to write to an excel (.xls MS Excel 2003 format) file programatically using Java. The excel output files may contain ~200,000 rows which I plan to split over number of sheets (64k rows per sheet, due to the excel limit).

I have tried using the apache POI APIs but it seems to be a memory hog due to the API object model. I am forced to add cells/sheets to the workbook object in memory and only once all data is added, I can write the workbook to a file! Here is a sample of how the apache recommends i write excel files using their API:

Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");

//Create a row and put some cells in it
Row row = sheet.createRow((short)0);

// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

Clearly, writing ~20k rows(with some 10-20 columns in each row) gives me the dreaded "java.lang.OutOfMemoryError: Java heap space".

I have tried increasing JVM initial heapsize and max heap size using Xms and Xmx parameters as Xms512m and Xmx1024. Still cant write more than 150k rows to the file.

I am looking for a way to stream to an excel file instead of building the entire file in memory before writing it to disk which will hopefully save a lot of memory usage. Any alternative API or solutions would be appreciated, but I am restricted to usage of java. Thanks! :)

like image 809
Jaskirat Avatar asked Sep 28 '09 09:09

Jaskirat


People also ask

How do I make a large Excel file?

To switch the default paper size, go to Page Layout > Page Setup > Size, and then choose the size you want.

How can I have more than 1 million rows in Excel?

You may generate large csv file yourself manually - save about million of rows from excel as csv, open such csv in Notepad, copy and add or add manually another half millions of rows or so, close the file.


1 Answers

Try to use SXSSF workbook, thats great thing for huge xls documents, its build document and don't eat RAM at all, becase using nio

like image 179
Serhii Bohutskyi Avatar answered Oct 12 '22 22:10

Serhii Bohutskyi