When generating large Excel report by using JasperReports and DynamicJasper, have to take note the following configuration.
- Java Heap Size
- VIRTUALIZER
- IS_IGNORE_PAGINATION
Check out the following example code.
public class JasperExcelReport {
protected JasperPrint jp;
protected JasperReport jr;
protected Map params = new HashMap();
protected DynamicReport dr;
public void buildReport() throws Exception {
DynamicReportBuilder drb = new DynamicReportBuilder();
for (int i = 1; i <= 10; i++) {
AbstractColumn column = ColumnBuilder.getInstance()
.setColumnProperty("Column" + i, String.class.getName())
.setTitle("Column " + i + " Title").setWidth(200).build();
drb.addColumn(column);
}
drb.setUseFullPageWidth(true);
dr = drb.build();
JRDataSource ds = getDataSource();
// Make sure Java Heap Size is set.
// E.g. "-Xms256m -Xmx1024m"
// Virtualizer convert the page and store into a physical files on harddisk.
JRFileVirtualizer virtualizer = new JRFileVirtualizer(100, "C://tmp");
params.put(JRParameter.REPORT_VIRTUALIZER, virtualizer);
System.out.println("Generating...");
jr = DynamicJasperHelper.generateJasperReport(dr, new ClassicLayoutManager(), params);
System.out.println("Filling...");
if (ds != null) {
// JRParameter.IS_IGNORE_PAGINATION default is false,
// if you set to true, virtualizer will not work.
params.put(JRParameter.IS_IGNORE_PAGINATION, new Boolean(false));
jp = JasperFillManager.fillReport(jr, params, ds);
} else {
jp = JasperFillManager.fillReport(jr, params);
}
// If column width more then page width, some column will merge automatically.
// Set the page width to resolve this issue.
//jp.setPageWidth(0);
//jp.setPageHeight(0);
FileOutputStream fileOut = new FileOutputStream("C:/tmp/ExcelReport.xls");
JRExporter exporter = new JExcelApiExporter();
exporter.setParameter(JExcelApiExporterParameter.OUTPUT_STREAM, fileOut);
exporter.setParameter(JExcelApiExporterParameter.JASPER_PRINT, jp);
System.out.println("Exporting...");
exporter.exportReport();
fileOut.flush();
fileOut.close();
}
protected JRDataSource getDataSource() {
// Generate dummy data to show in the report.
List records = new ArrayList();
for (int i = 1; i < 500000; i++) {
Map columns = new HashMap();
for (int j = 1; j <= 10; j++) {
System.out.println("Column" + j);
// The HashMap Key must save with ColumnProperty Name
columns.put("Column" + j, "Record " + i + " Column " + j + " data.");
}
records.add(columns);
}
JRDataSource ds = new JRMapCollectionDataSource(records);
return ds;
}
public static void main(String[] args) throws Exception {
JasperExcelReport jer = new JasperExcelReport();
jer.buildReport();
System.out.println("Done");
}
}
No comments:
Post a Comment