Tuesday, May 1, 2012


Now we can create large excel document(large excel report) in java without "heap out of memory error". This tutorial is based on apache poi 3.8 which is latest version of poi api. POI3.8 api an API-compatible streaming extension of XSSF to be used when very large spreadsheets have to be produced, and heap space is limited.

Below Example:
package com.excel;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

public class CreateLargeDocument {

public static void main(String[] args) throws Throwable {
Workbook wb = new SXSSFWorkbook(100); // keep 100 rows in memory, exceeding rows will be flushed to disk
Sheet sh = wb.createSheet();
for(int rownum = 0; rownum < 1000; rownum++){
Row row = sh.createRow(rownum);
for(int cellnum = 0; cellnum < 10; cellnum++){
Cell cell = row.createCell(cellnum);
String address = new CellReference(cell).formatAsString();
cell.setCellValue(address);
}
}

FileOutputStream out = new FileOutputStream("C:/temp/sxssf.xlsx");
wb.write(out);
out.close();
}
}
create a folder "temp" in your c drive.
add following jar to build path in eclipse:
required_jar
This api tested with 30 column for 1000000 rows of excel document it does not through "heap out of memory error" and work without any heavy load.