Dynamic Jasper

In Jasper reports the creation of the Jrxml template is tedious and it takes some time to learn. You need to use some kind of tool like iReport to create the Jasper templates and then use them. Maintaining and modifying will not be easy till you master it. And using this for dynamic report become difficult and dynamically creating the Jrxml programmatically is a challenging task.

For such needs Dynamic Jasper is available for rescue. This reduces the complexity of creating Jrxml templates manually. We will be able to generate Jrxml programmatically using API. Also the reports can be generated on the fly by defining the columns at run time. This is so much flexible that the columns, column width, font, and styles every thing can be dynamic. Also it is flexible you will be able to reuse the existing Jrxml templates.

The Dynamic Jasper report support many output formats like Excel, CVS, XML, PDF, HTML , RTF, Text etc.. It supports many data sources like JDBC, Hibernate, EJB, Java Bean etc.,

Let us learn from examples. You may refer http://www.dynamicjasper.com to know more about this. Here I will try to give a simple example to begin with and understand.

Let us begin with a simple excel report.
We are generating Sales Report for November and December 2006.

Create DynamicDemoBean
We create a new Bean class DynamicDemoBean.java which we will be using to pass data for report generation.

package src;

public class DynamicDemoBean {
private String state;
private String branch;
private String productLine;
private String item;
private long itemCode;
private long quantity;
private float amount;
private String remarks;

public DynamicDemoBean(float amount, String branch, long itemCode,
String item, String line, long quantity, String state, String remarks) {
super();
this.amount = amount;
this.branch = branch;
this.itemCode = itemCode;
this.item = item;
productLine = line;
this.quantity = quantity;
this.state = state;
this.remarks = remarks;
}

public float getAmount() {
return amount;
}
public void setAmount(float amount) {
this.amount = amount;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public long getItemCode() {
return itemCode;
}
public void setItemCode(long itemCode) {
this.itemCode = itemCode;
}
public String getProductLine() {
return productLine;
}
public void setProductLine(String productLine) {
this.productLine = productLine;
}
public long getQuantity() {
return quantity;
}
public void setQuantity(long quantity) {
this.quantity = quantity;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}

public String getRemarks() {
return remarks;
}

public void setRemarks(String remarks) {
this.remarks = remarks;
}

}

Dynamically Create Report

Here we are planning to generate an Excel report. We generate JasperPrint object dynamically and using this we create the excel report.

You may refer the getFirstReport() method where the columns are dynamically created and added. As there are no jrxml files are used the styles need to be created and applied for columns, headers etc. Dynamically adding columns can be very easy too.

public class DynamicJasper {
/**
* @param args
*/
public static void main(String[] args) {

try{
//build report
JasperPrint jp = buildReport();

//export report
JExcelApiExporter exporter = new JExcelApiExporter();

exporter.setParameter(JExcelApiExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);

exporter.setParameter(JExcelApiExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
exporter.setParameter(JExcelApiExporterParameter.JASPER_PRINT, jp);
exporter.setParameter(JExcelApiExporterParameter.OUTPUT_FILE_NAME, “e:/dynamicDemo.xls”);
exporter.setParameter(JExcelApiExporterParameter.IGNORE_PAGE_MARGINS,
Boolean.TRUE);
exporter.setParameter(JExcelApiExporterParameter.OFFSET_X, 0);
exporter.setParameter(JExcelApiExporterParameter.IS_IGNORE_CELL_BORDER, Boolean.FALSE);
exporter.setParameter(JRXlsExporterParameter.SHEET_NAMES, new String[]{“November”, “December”});
exporter.exportReport();

}catch(JRException je){
je.printStackTrace();
}catch(ColumnBuilderException ce){
ce.printStackTrace();
}catch(ClassNotFoundException cfe){
cfe.printStackTrace();
}

}

private static JasperPrint buildReport() throws ColumnBuilderException, JRException, ClassNotFoundException{
Style headerStyle = getHeaderStyle();
Style detailStyle = new Style();
detailStyle.setBorder(Border.THIN);

//build first report
FastReportBuilder firstReport = getFirstReport(headerStyle, detailStyle);
DynamicReport firstDynaRep = firstReport.build();

//build second report
FastReportBuilder secondReport = getSecondReport(headerStyle, detailStyle);
DynamicReport secondDynaRep = secondReport.build();

//Prepare data
Object[] obj = new Object[3];

obj[0]= new DynamicDemoBean(100.00f, “San Jose”, 200, “Tojo”, “Vintage 2000”, 50, “CA”, “Tojo is a finer veriety of wine produced from the California wine yards. It has been produced to the industy standards. Tojo is a finer veriety of wine produced from the California wine yards. It has been produced to the industy standards.”);

obj[1]= new DynamicDemoBean(110f, “San Jose”, 120, “Spinster”, “Vintage 2000”, 50, “CA”, “Spinster is a finer veriety of wine produced from the California wine yards. It has been produced to the industy standards.”);

obj[2]= new DynamicDemoBean(120.00f, “Down Town”, 220, “Royal”, “Vintage 2000”, 50, “CA”, “Royal is a finer veriety of wine produced from the California wine yards. It has been produced to the industy standards.”);

//generate jasper print dynamically
JasperPrint jp = DynamicJasperHelper.generateJasperPrint(firstDynaRep, new ClassicLayoutManager(), new JRBeanArrayDataSource(obj));

JasperPrint jp1 = DynamicJasperHelper.generateJasperPrint(secondDynaRep, new ClassicLayoutManager(), new JRBeanArrayDataSource(obj));
//Combine pages
List pages = new ArrayList(jp1.getPages());
int i=1;
for(int count=0;count<pages.size();count++){
jp.addPage(i, (JRPrintPage)pages.get(count));
i++;
}
return jp;
}

private static Style getHeaderStyle(){
Style headerStyle = new Style();
headerStyle.setFont(Font.ARIAL_MEDIUM_BOLD);
headerStyle.setBorderBottom(Border.PEN_2_POINT);
headerStyle.setHorizontalAlign(HorizontalAlign.CENTER);
headerStyle.setVerticalAlign(VerticalAlign.MIDDLE);
headerStyle.setBackgroundColor(Color.LIGHT_GRAY);
headerStyle.setTextColor(Color.BLUE);
headerStyle.setTransparency(Transparency.OPAQUE);
return headerStyle;
}

private static AbstractColumn getColumn(String property, Class type,
String title, int width, Style headerStyle, Style detailStyle)
throws ColumnBuilderException {
AbstractColumn columnState = ColumnBuilder.getInstance()
.setColumnProperty(property, type.getName()).setTitle(
title).setWidth(Integer.valueOf(width))
.setStyle(detailStyle).setHeaderStyle(headerStyle).build();
return columnState;
}

private static FastReportBuilder getFirstReport(Style headerStyle, Style detailStyle) throws ColumnBuilderException, ClassNotFoundException{
FastReportBuilder firstReport = new FastReportBuilder();

AbstractColumn columnState = getColumn("state", String.class,
"State", 30, headerStyle, detailStyle);
AbstractColumn columnBranch = getColumn("branch", String.class,
"Branch", 30, headerStyle, detailStyle);
AbstractColumn columnProductLine = getColumn("productLine", String.class,
"Product Line", 50, headerStyle, detailStyle);
AbstractColumn columnItem = getColumn("item", String.class,
"Item", 50, headerStyle, detailStyle);
AbstractColumn columnaItemCode = getColumn("itemCode", Long.class,
"Item Code", 22, headerStyle, detailStyle);
AbstractColumn columnQuantity = getColumn("quantity", Long.class,
"Quantity", 22, headerStyle, detailStyle);
Style amountStyle = new Style();
amountStyle.setHorizontalAlign(HorizontalAlign.RIGHT);
AbstractColumn columnAmount = ColumnBuilder.getInstance()
.setColumnProperty("amount", Float.class.getName())
.setTitle("Amount").setWidth(Integer.valueOf(30))
.setStyle(amountStyle).setPattern("$ 0.00")
.setStyle(detailStyle).setHeaderStyle(headerStyle).build();

AbstractColumn remarks = getColumn("remarks", String.class,
"Remarks", 100, headerStyle, detailStyle);
firstReport.addColumn(columnState)
.addColumn(columnBranch)
.addColumn(columnProductLine)
.addColumn(columnItem)
.addColumn(columnaItemCode)
.addColumn(columnQuantity)
.addColumn(columnAmount)
.addColumn(remarks);

firstReport.addFirstPageImageBanner("C:\\eclipse\\workspace\\DynamicJasperReports\\src\\fdvsolutions_dynamicjasper_project.png", Integer.valueOf(560), Integer.valueOf(51), ImageBanner.ALIGN_LEFT);
firstReport.setTitle("November 2006 sales report");
firstReport.setSubtitle("This report was generateed at");
firstReport.setUseFullPageWidth(true); //make colums to fill the page width

return firstReport;
}

private static FastReportBuilder getSecondReport(Style headerStyle, Style detailStyle) throws ColumnBuilderException{
FastReportBuilder secondReport = new FastReportBuilder();

AbstractColumn columnState = getColumn("state", String.class,
"State", 30, headerStyle, detailStyle);
AbstractColumn columnBranch = getColumn("branch", String.class,
"Branch", 30, headerStyle, detailStyle);
AbstractColumn columnProductLine = getColumn("productLine", String.class,
"Product Line", 50, headerStyle, detailStyle);
AbstractColumn columnItem = getColumn("item", String.class,
"Item", 50, headerStyle, detailStyle);
AbstractColumn columnaItemCode = getColumn("itemCode", Long.class,
"Item Code", 22, headerStyle, detailStyle);
AbstractColumn columnQuantity = getColumn("quantity", Long.class,
"Quantity", 22, headerStyle, detailStyle);
Style amountStyle = new Style();
amountStyle.setHorizontalAlign(HorizontalAlign.RIGHT);
AbstractColumn columnAmount = ColumnBuilder.getInstance()
.setColumnProperty("amount", Float.class.getName())
.setTitle("Amount").setWidth(Integer.valueOf(30))
.setStyle(amountStyle).setPattern("$ 0.00")
.setStyle(detailStyle).setHeaderStyle(headerStyle).build();

AbstractColumn remarks = getColumn("remarks", String.class,
"Remarks", 100, headerStyle, detailStyle);
secondReport.addColumn(columnState);
secondReport.addColumn(columnBranch);
secondReport.addColumn(columnProductLine);
secondReport.addColumn(columnItem);
secondReport.addColumn(columnaItemCode);
secondReport.addColumn(columnQuantity);
secondReport.addColumn(columnAmount);
secondReport.addColumn(remarks);

secondReport.addFirstPageImageBanner("C:\\eclipse\\workspace\\DynamicJasperReports\\src\\fdvsolutions_dynamicjasper_project.png", Integer.valueOf(560), Integer.valueOf(51), ImageBanner.ALIGN_LEFT);
secondReport.setTitle("December 2006 sales report");
secondReport.setSubtitle("This report was generateed at");
secondReport.setUseFullPageWidth(true); //make colums to fill the page width

return secondReport;
}

}

Jasper Reports is an open source reporting library which is available for windows and linux platforms. The Jasper report support many output formats like Excel, CVS, XML, PDF, HTML , RTF, Text etc..

It also supports many data sources like JDBC, Hibernate, EJB, Java Bean etc.,
The Jasper Report can be used on the web and also it can be used from simple Java application. It vastly supports the presentation formats like Dashboards, tables, cross tabs, and charts. Basically open and standards based Java and Xml. Supported by the most active community of report designers and developers.

The Jasper report simplifies the solution by providing support for multiple data sources, sub reports and cross tab reports. The built in virtualization capability of Jasper enables efficiently rendering large reports with limited available disk storage resources.

Report Life Cycle
• Jrxml file contain the report structure information.
• Jrxml file is converted into JasperDesign object by JRXmlLoader.
• JasperCompileManager parses the jrxml file and compiles it to JasperReport file. This file does not contain any data.
• JasperFillManager fills the data which is passed from various data sources.
• Using JRXlsExporter the excel file is generated.

Templates
Jasper uses jrxml templates to build and render the report. The jrxml is a standards based xml which can be dynamically generated using the open source tool iReport. iReport is the tool which can be used to generate the jrxml templates which can be connected to various data sources like JDBC, XML, Hibernate etc., Jrxml file contain the report structure information.

Report Basics
There are some basic steps involved in creating a Jasper Report. We will discuss a report generation steps for Excel output.

• Designing the Jasper Template.
• Compile Jasper Report.
• Fill Jasper Report using a data source.
• Export the Report.

We will discuss how each of the above operations can be done using a simple report. Our report uses Java Bean as the data source and generates multiple sheet Excel Report.

Designing the Jasper Template
Designing of Jasper Report involves generation of the Report Template, which is an Xml file with ‘jrxml’ extension. This template is a unique xml file which can be designed using an open source tool called iReport. It is very simple to design using the iReport tool. But once we understand the format, tags and attributes, it is very easy to edit manually.

Let us briefly discuss about the design of a simple template using iReport tool. iReport provides options to include Title, Page Header, Column Header, Detail, Column Footer etc., as per our requirement. Also there are options like Page Number, Total Pages, Page x of y, Sum, Current Date and percentage which can be inserted where ever needed. In our report template we just have the Column Header and details.
If you scrutiny the sample jrxml file given below, you will find the <jasperReport> tag with attributes like name, column count, page width, margins etc., which are specific to a report. Title and Page Header tags specify Title and Page Header information.
Column Headers are defined using an element called ‘Static Text’. For each Static Text element the cell level properties are defined using the tag ‘Report Element’. The cell type like Transparent or Opaque can be assigned using the attribute ‘mode’ of the ‘reportElement’ tag. Attributes x, y, width and height are so important for positioning and size of the cell. If you make a small mistake in any of the value, the entire report structure will be misaligned. You can specify a background color using ‘backcolor’ attribute but if you want to specify a background color, you must have the mode as Opaque.
It is not necessary to know the tags and attributes of the jrxml file, but if you know them basics it will be easy to fine tune the report and you will be able to identify the problem in case of any issues.

So far we have completed how the Header row is built in jrxml template. Now we will have a look at how the detail rows are built.

We will be using the ‘detail’ tag to display the detail rows. We use ‘textField’ tag and ‘textFieldExpression’ tag is used in which the field name is passed. For example ‘personName’ is the field we are using. Firstly you need to create a field by that name specifying the type of the field.

<field name=”personName” class=”java.lang.String”/>

Later in the ‘textFieldExpression’ tag you need to specify the field name as shown below.

<textFieldExpression class=”java.lang.String”><![CDATA[$F{personName}]]></textFieldExpression>

Go through the jrxml file details given below and try to understand the structure and usage of various tags and attributes. A faster way to learn is by experimenting it using iReport. When ever you change some thing using iReport, the jrxml file is getting modified.

Simple jrxml file.

<?xml version=”1.0″ encoding=”UTF-8″ ?>
<!– Created with iReport – A designer for JasperReports –>
<!DOCTYPE jasperReport PUBLIC “//JasperReports//DTD Report Design//EN” “http://jasperreports.sourceforge.net/dtds/jasperreport.dtd”&gt;
<jasperReport
name=”FirstReport”
columnCount=”1″
printOrder=”Vertical”
orientation=”Portrait”
pageWidth=”595″
pageHeight=”842″
columnWidth=”555″
columnSpacing=”0″
leftMargin=”20″
rightMargin=”20″
topMargin=”30″
bottomMargin=”30″
whenNoDataType=”NoPages”
isTitleNewPage=”false”
isSummaryNewPage=”false”>
<property name=”ireport.scriptlethandling” value=”0″ />
<property name=”ireport.encoding” value=”UTF-8″ />
<import value=”java.util.*” />
<import value=”net.sf.jasperreports.engine.*” />
<import value=”net.sf.jasperreports.engine.data.*” /><field name=”personName” class=”java.lang.String”/>
<field name=”country” class=”java.lang.String”/>
<field name=”state” class=”java.lang.String”/>
<field name=”city” class=”java.lang.String”/><background>
<band height=”0″ isSplitAllowed=”true” >
</band>
</background>
<title>
<band height=”0″ isSplitAllowed=”true” >
</band>
</title>
<pageHeader>
<band height=”0″ isSplitAllowed=”true” >
</band>
</pageHeader>
<columnHeader>
<band height=”23″ isSplitAllowed=”false” >
<staticText>
<reportElement
mode=”Opaque”
x=”0″
y=”0″
width=”200″
height=”20″
backcolor=”#CCCCCC”
key=”staticText”/>
<box> <pen lineWidth=”0.5″/>
<topPen lineWidth=”0.5″/>
<leftPen lineWidth=”0.5″/>
<bottomPen lineWidth=”0.5″/>
<rightPen lineWidth=”0.5″/>
</box>
<textElement textAlignment=”Center” verticalAlignment=”Middle” rotation=”None” lineSpacing=”Single”>
<font fontName=”Arial” size=”10″ isBold=”true” isItalic=”false” isUnderline=”false” isStrikeThrough=”false” />
</textElement>
<text><![CDATA[Name]]></text>
</staticText>
<staticText>
<reportElement
mode=”Opaque”
x=”200″
y=”0″
width=”100″
height=”20″
backcolor=”#CCCCCC”
key=”staticText”/>
<box> <pen lineWidth=”0.5″/>
<topPen lineWidth=”0.5″/>
<leftPen lineWidth=”0.5″/>
<bottomPen lineWidth=”0.5″/>
<rightPen lineWidth=”0.5″/>
</box>
<textElement textAlignment=”Center” verticalAlignment=”Middle” rotation=”None” lineSpacing=”Single”>
<font fontName=”Arial” size=”10″ isBold=”true” isItalic=”false” isUnderline=”false” isStrikeThrough=”false” />
</textElement>
<text><![CDATA[Country]]></text>
</staticText>
<staticText>
<reportElement
mode=”Opaque”
x=”300″
y=”0″
width=”100″
height=”20″
backcolor=”#CCCCCC”
key=”staticText”/>
<box> <pen lineWidth=”0.5″/>
<topPen lineWidth=”0.5″/>
<leftPen lineWidth=”0.5″/>
<bottomPen lineWidth=”0.5″/>
<rightPen lineWidth=”0.5″/>
</box>
<textElement textAlignment=”Center” verticalAlignment=”Middle” rotation=”None” lineSpacing=”Single”>
<font fontName=”Arial” size=”10″ isBold=”true” isItalic=”false” isUnderline=”false” isStrikeThrough=”false” />
</textElement>
<text><![CDATA[State]]></text>
</staticText>
<staticText>
<reportElement
mode=”Opaque”
x=”400″
y=”0″
width=”100″
height=”20″
backcolor=”#CCCCCC”
key=”staticText”/>
<box> <pen lineWidth=”0.5″/>
<topPen lineWidth=”0.5″/>
<leftPen lineWidth=”0.5″/>
<bottomPen lineWidth=”0.5″/>
<rightPen lineWidth=”0.5″/>
</box>
<textElement textAlignment=”Center” verticalAlignment=”Middle” rotation=”None” lineSpacing=”Single”>
<font fontName=”Arial” size=”10″ isBold=”true” isItalic=”false” isUnderline=”false” isStrikeThrough=”false” />
</textElement>
<text><![CDATA[City]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height=”24″ isSplitAllowed=”false” >
<textField isStretchWithOverflow=”true” pattern=”” isBlankWhenNull=”true” evaluationTime=”Now” hyperlinkType=”None” hyperlinkTarget=”Self” >
<reportElement
x=”0″
y=”0″
width=”200″
height=”18″
key=”textField”/>
<box> <pen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<topPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<leftPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<bottomPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<rightPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
</box>
<textElement>
<font/>
</textElement>
<textFieldExpression class=”java.lang.String”><![CDATA[$F{personName}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow=”false” isBlankWhenNull=”false” evaluationTime=”Now” hyperlinkType=”None” hyperlinkTarget=”Self” >
<reportElement
x=”200″
y=”0″
width=”100″
height=”18″
key=”textField”/>
<box> <pen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<topPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<leftPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<bottomPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<rightPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
</box>
<textElement>
<font/>
</textElement>
<textFieldExpression class=”java.lang.String”><![CDATA[$F{country}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow=”true” isBlankWhenNull=”false” evaluationTime=”Now” hyperlinkType=”None” hyperlinkTarget=”Self” >
<reportElement
x=”300″
y=”0″
width=”100″
height=”18″
key=”textField”/>
<box> <pen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<topPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<leftPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<bottomPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<rightPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
</box>
<textElement>
<font/>
</textElement>
<textFieldExpression class=”java.lang.String”><![CDATA[$F{state}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow=”true” isBlankWhenNull=”false” evaluationTime=”Now” hyperlinkType=”None” hyperlinkTarget=”Self” >
<reportElement
x=”400″
y=”0″
width=”100″
height=”18″
key=”textField-1″/>
<box> <pen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<topPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<leftPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<bottomPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<rightPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
</box>
<textElement>
<font/>
</textElement>
<textFieldExpression class=”java.lang.String”><![CDATA[$F{city}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band height=”0″ isSplitAllowed=”true” >
</band>
</columnFooter>
<pageFooter>
<band height=”0″ isSplitAllowed=”true” >
</band>
</pageFooter>
<summary>
<band height=”0″ isSplitAllowed=”true” >
</band>
</summary>
</jasperReport>

Compile Jasper Report

import java.util.HashMap;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;public class CompileReport {
public static void main(String[] args) {
//JasperReport jasperReport;
JasperPrint jasperPrint;
try {
JasperCompileManager.compileReportToFile(“C:\\eclipse\\workspace\\NewJasper\\src\\FirstJasper.jrxml”);
JasperCompileManager.compileReportToFile(“C:\\eclipse\\workspace\\NewJasper\\src\\SecondJasper.jrxml”);}
catch (JRException e) {
e.printStackTrace();
}
}
}
In the above example we have two jrxml templates, one for each sheet in our excel report. We assume that we have completed the design of both of our jrxml templates. The next step is to compile them.

JasperCompileManager.compileReportToFile(“C:\\eclipse\\workspace\\NewJasper\\src\\FirstJasper.jrxml”);

Just call the method compileReportToFile of JasperCompileManager by passing the jrxml file name (FirstJasper.jrxml). The report gets compiled and a new FirstJasper.jasper file is generated.

Fill Jasper Report using a data source

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRPrintPage;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;public class ExportDemoExcel {
public static void main(String args[]){
try {
Object[] objArr = new Object[3];
objArr[0]= new DemoBean(“Ramesh”,”USA”,”CA”, “San Jose”, “Jasper Report”, 2, “San Jose”, “Expert”);
objArr[1]= new DemoBean(“Suresh”,”USA”,”CA”, “San Jose”, “Jasper Report”, 2, “San Jose”, “Expert”);
objArr[2]= new DemoBean(“Paul”,”USA”,”CA”, “San Jose”, “Jasper Report”, 2, “San Jose”, “Expert”);
JasperPrint jp1 = JasperFillManager.fillReport(“C:\\eclipse\\workspace\\NewJasper\\src\\FirstReport.jasper”, new HashMap(), new JRBeanArrayDataSource(objArr));
JasperPrint jp2 = JasperFillManager.fillReport(“C:\\eclipse\\workspace\\NewJasper\\src\\SecondReport.jasper”, new HashMap(), new JRBeanArrayDataSource(objArr));
List<JRPrintPage> pages = new ArrayList<JRPrintPage>(jp2.getPages());
int i=1;
for(int count=0;count<pages.size();count++){
jp1.addPage(i, (JRPrintPage)pages.get(count));
i++;
}JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameter(JRXlsExporterParameter.
IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
Boolean.TRUE);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp1);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
“e:/demo1.xls”);
exporter.setParameter(JRXlsExporterParameter.SHEET_NAMES, new String[]{”Personal Information”, “Skills”});
exporter.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS,
Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.OFFSET_X, 0);
exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_CELL_BORDER, Boolean.FALSE);
exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, true);
exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, false);
exporter.exportReport();

} catch (JRException e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace();
}
}
}

We are using the Java Bean as the data source. The next operation will be filling the report.

JasperPrint jp1 = JasperFillManager.fillReport(“C:\\eclipse\\workspace\\NewJasper\\src\\FirstReport.jasper”, new HashMap(), new JRBeanArrayDataSource(obj));

Just call the ‘fillReport’ method of the ‘JasperFillManager’ class by passing the jasper file name and the data source. In our case the data source is an Object Array containing the Java Beans. Make a note that the field names which we use in the template should match the Java Bean attribute, otherwise it will through an error. When the fill operation is successful, file is generated with the jrpint extension. In our case it will be FirstReport.jrprint.

Adding multiple Sheets in our excel report

List<JRPrintPage> pages = new ArrayList<JRPrintPage>(jp2.getPages());
int i=1;
for(int count=0;count<pages.size();count++){
jp1.addPage(i, (JRPrintPage)pages.get(count));
i++;

In our case we use two jrxml files one for each sheet. There fore there two jrprint file are generated. In the above code we just adding the sheets to the report.

Export Excel

JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
Boolean.FALSE);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp1);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
“e:/demo1.xls”);
//Pass the sheet names
exporter.setParameter(JRXlsExporterParameter.SHEET_NAMES, new String[]{”Personal Information”, “Skills”});
exporter.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS,
Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.OFFSET_X, 0);
exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_CELL_BORDER, Boolean.FALSE);
exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, true);
exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, false);
exporter.exportReport();

Before exporting a report we are passing some export parameters as shown above. This is because by default these parameters have some initial values and that may affect the appearance of our report. The report file is exported and stored in the specified path.