Jasper Report for beginners

July 20, 2008

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.

About these ads

13 Responses to “Jasper Report for beginners”

  1. Senthil said

    Hi
    Multisheet is not generating, is printing one sheet both reports.plesae let me know any changes I have to do..

  2. chellaganesh said

    Are you adding the pages using the addPage method? Basically we use different templates for each page and bind them to a book using addPage method.

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

    Also you need to set this parameter to specify one page per sheet to false.
    exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
    Boolean.FALSE);

    Can you please paste your code related to export here.

  3. Senthil said

    Thanks of your reply, I have done above mentioned changes, eventhough its generating one sheet. (it containing two reports ie one by one)

    I have pasted the code below. please let me know what is mistake.
    try {
    ReportBO reportBO= (ReportBO) ServiceFinder.findBean(REPORT_BO_IMPL);

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
    FacesContext context = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();

    lookpParameterIDs=reportBO.getCreditCheckReport(this.fromdate, this.todate,this.selectDepartment,this.lookupName,this.lookedupIDs,”F”);
    //FIRST XML FILE
    String xml1 = servletContext.getRealPath(“/jsp/pages/reportsxml/CreditCheckReport_Company.xml”);
    InputStream input = new FileInputStream(new File(xml1));
    ServletOutputStream servletOutputStream =response.getOutputStream();
    JasperDesign design = JRXmlLoader.load(input);
    JasperReport report1 = JasperCompileManager.compileReport(design);

    JasperPrint jp1 = JasperFillManager.fillReport(report1, new HashMap(), new JRBeanCollectionDataSource(lookpParameterIDs));
    lookpParameterIDs=reportBO.getCreditCheckReport(this.fromdate, this.todate,this.selectDepartment,this.lookupName,this.lookedupIDs,”P”);

    //SECOND XML FILE
    String xml2 = servletContext.getRealPath(“/jsp/pages/reportsxml/CreditCheckReport_Person.xml”);
    input = new FileInputStream(new File(xml2));
    design = JRXmlLoader.load(input);
    JasperReport report2 = JasperCompileManager.compileReport(design);
    JasperPrint jp2 = JasperFillManager.fillReport(report2, new HashMap(), new JRBeanCollectionDataSource(lookpParameterIDs));

    List pages = new ArrayList(jp2.getPages());
    pages = new ArrayList(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();
    byte[] bytes = null;
    ByteArrayOutputStream xlsReport = new ByteArrayOutputStream();
    ResourceBundle bundle=ResourceBundle.getBundle(“resources/config”);
    String generateLocation=bundle.getString(“outputxls”);
    OutputStream output = new FileOutputStream(new File(generateLocation));
    JRXlsExporter exporter1 = new JRXlsExporter();

    exporter1.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.TRUE);
    exporter1.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.FALSE);
    exporter1.setParameter(JRXlsExporterParameter.JASPER_PRINT, jp1);
    exporter1.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, xlsReport);
    exporter1.setParameter(JRXlsExporterParameter.SHEET_NAMES, new String[]{“Individual”, “Company”});
    exporter1.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS,Boolean.TRUE);
    exporter1.setParameter(JRXlsExporterParameter.OFFSET_X, 0);
    exporter1.setParameter(JRXlsExporterParameter.IS_IGNORE_CELL_BORDER, Boolean.FALSE);
    exporter1.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
    exporter1.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, false);
    exporter1.exportReport();
    bytes = xlsReport.toByteArray();

    // FOR DOWNLOAD AND MAIL FUNCTIONALITY

    if(this.download) {
    response.setContentType(“application/vnd.ms-excel”);
    response.setHeader(“Content-disposition”, “attachment; filename=” + reportName +”_”+DateTimeUtil.formatDate(today,”yyyyMMdd”)+”.xls”);
    context.responseComplete();
    output.write(xlsReport.toByteArray());
    ServletOutputStream outputStream1 = response.getOutputStream();
    outputStream1.write(bytes);
    context.renderResponse();
    servletOutputStream.flush();
    servletOutputStream.close();

    Email.sendEmail(to, from, attachment,this.reportName);
    }else{
    output.write(xlsReport.toByteArray());
    Email.sendEmail(to, from, attachment,this.reportName);
    this.mailSent();
    }

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

    Thanks
    Senthil

  4. Vengadesh said

    Hai,

    I have created a report that is given more than ouput .

    But, I need a select box option that is used to select option that is input parameter . it is used in our application .but , i do not know that it is possible or nor in ireport 2.0.2 . Please tell me or send the mail my personal mail id if u done the problems

  5. Senthil said

    Hi
    Still I have the same issue, please help me to resolve..

    Thanks
    Senthil

  6. chellaganesh said

    I just analyzed your code and found that the following code create the issue.

    exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
    Boolean.FALSE);

    I just modified it as TRUE, now it is working fine.

    exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
    Boolean.TRUE);

  7. ganesh said

    hi chellaganesh,
    i want to dynamically pass a value for showing a sheet name…pls help me out

    • chellaganesh said

      exporter1.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,Boolean.TRUE);
      exporter1.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.FALSE);
      exporter1.setParameter(JRXlsExporterParameter.JASPER_PRINT, jp1);
      exporter1.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, xlsReport);
      exporter1.setParameter(JRXlsExporterParameter.SHEET_NAMES, new String[]{”Individual”, “Company”});

      Hi Ganesh,
      Please refer the above code snippet. We are passing the sheet names as an array to the exporter. You just build or load the array dinamically and pass it.

  8. Rajan said

    How to create dynamic report using IReport?

    Because we are developing a Swing based project in java. We need solution for dynamic report generation. In my swing design i will select some column at run-time based on that input i have to create a report at run-time.

    note:
    How to create .jrxml file for run-time(its possible).
    In net i found some solution for dynamic jasper, but there also they create columns using .addColumn();, but it need the .jrxml file.

    give some solution as soon as possible

    • chellaganesh said

      Rajan,
      It is better to use DynamicJasper for creating Jasper Reports dynamically. I understand that you will be having a Swing application which user will be using to select columns and then create reports on the fly. I don’t think we need to generate Jrxml manually for such needs.

      Please go thru the documentation for Dynamic Jasper and let me know if you have any queries. http://dynamicjasper.sourceforge.net/

  9. Smita Rao said

    Hi Chellaganesh,

    We have a requirement for jasper reports where we need to output the data of 2 jrxml’s(2 queries) in 2 sheets of a single workbook in excel.Can you pleae let us know what would be code changes for the same.The output of the queries might result in number of pages of data.However we need only 2 sheets in workbook .The individual sheet might contain number of pages.Please guide.Its urgent.

    Thanks,
    Smita Rao

  10. chellaganesh said

    I hope you are familiar with creating the two jrxml files using iReport.

    Compile the two jrxml files.

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

    Data Source
    There is a default implementation of this interface, the JRResultSetDataSource class, which wraps a java.sql.ResultSet object. It allows the use of any relational database through JDBC.
    When using a JDBC data source, you could pass a java.sql.Connection object to the report filling operations and specify the query in the report definition itself (see the element in the XML file) or could create a new instance of the JRResultSetDataSource by supplying the java.sql.ResultSet object directly.

    //Get a valid connection
    Connection conn = DBConnectionFactory.getConnection();

    stmt = conn.createStatement();
    rset_1 = stmt.executeQuery (queryString_1);
    rset_2 = stmt.executeQuery (queryString_2);

    //Use a valid connection
    JasperPrint jp1 = JasperFillManager.fillReport(“C:\\eclipse\\workspace\\NewJasper\\src\\FirstReport.jasper”, new HashMap(),new JRResultSetDataSource(rset_1));

    JasperPrint jp2 = JasperFillManager.fillReport(“C:\\eclipse\\workspace\\NewJasper\\src\\SecondReport.jasper”, new HashMap(),new JRResultSetDataSource(rset_2));

    //Refer the above code for adding multiple Sheets in our excel report

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

    The rest of the code is same.

  11. Ravi said

    Hi Ganesh,

    Your sample code is really useful. I can able to do a POC for our project with in 30 mins using your code. Thanks for your code and explanation.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: