AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1140&pId=-1
Creating Report Using JasperReports
page
by Anuva Das
Feedback
Average Rating: 
Views (Total / Last 10 Days): 109143/ 125

Introduction

JasperReports is a very popular open source report generating tool, written in pure Java and can be used to deliver dynamic content to the screen or printer. It can create reports in multiple formats, such as HTML file, PDF file, Excel file, CSV file , XML file, etc. It is capable of producing a report using data from a database, parameters, variables expressions and groups, etc. It also includes features, such as chart, crosstab, custom data sources, scriptlet, and subreport. Unfortunately, it is not clearly documented. I had a hard time creating a simple report. This tutorial demonstrates how to get started with JasperReports.

Requirements

To generate a report using JasperReports you will need following things:

·         Sun JDK 1.4 or Later version

·         jasperreports-{version}.jar

·         commons-beanutils-{version}.jar

·         commons-collections-{version}.jar

·         commons-digester-{version}.jar

·         commons-logging-{version}.jar

·         xercesImpl.jar-for parsing XML

·         itext-{version}.jar-For creating PDF formatted report

·         poi-{version}.jar-For creating XLS formatted report

·         If you want to access database, you must have to provide a JDBC driver.

·         Acrobat Reader

These are the minimum requirements for creating a report. You might have to add more JAR files for using other features of JasperReports. For example, to create a chart you have to add jfreechart-{version}.jar file. All these jar files are already included in the lib/dist directory of JasperReports, so you do not have to download these.

Preliminary Setup

1.    Install JDK 1.4 or higher version from http://java.sun.com/javase/downloads/index.jsp.

2.    Download jasperreports-1.3.0-project. zip or any other version of JasperReports from http://jasperreports.sourceforge.net. Then unzip it where you want.

3.    Download and install Adobe Acrobat Reader.

4.    Include the path for all the required jar files in the CLASSPATH variable.

Designing Report

JasperReports uses XML file for creating report. The user designs a report using respective XML tags and attributes, defined in a file called jasperreports.dtd. Save the file with a JRXML/XML extension. This file contains all the information about the report such as title, page headers and footers, column headers and footers, summary, query, fonts, images, report details, etc.

For example, the following XML template is used to design a report that will show the salesman details with a report title that has been given as a parameter.

Listing 1

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
 "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="demo">
<parameter name="Report_Title" class="java.lang.String"/> 
<queryString><![CDATA[select * from sales_master]]></queryString>
<field name="SALESMANNO" class="java.lang.String"/>
<field name="SALESMAN_NAME" class="java.lang.String"/>
<field name="CITY" class="java.lang.String"/>
<field name="STATE" class="java.lang.String"/>
<field name="QTY_SALES" class="java.math.BigDecimal"/>
<title>     
<band height="50" >
<textField >
<reportElement x="230" y="4" width="100" height="18"/> 
<textFieldExpression class="java.lang.String">
<![CDATA[$P{Report_Title}]]>
</textFieldExpression>  
</textField>
</band>
</title>
<columnHeader>
<band height="30">
<staticText>
<reportElement x="29" y="0" width="102" height="25"/> 
<text><![CDATA[Salesman Name]]></text>
</staticText>
<staticText>
<reportElement x="146" y="2" width="104" height="23"/>
<text><![CDATA[City]]></text>
</staticText>
<staticText>
<reportElement x="260" y="1" width="100" height="24"/> 
<text><![CDATA[State]]></text>
</staticText>
<staticText>
<reportElement x="383" y="1" width="94" height="23"/> 
<text><![CDATA[Quantity Sold]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="100">
<textField>
<reportElement x="28" y="8" width="100" height="29"/> 
<textFieldExpression class="java.lang.String">
<![CDATA[$F{SALESMAN_NAME}]]>
</textFieldExpression>
</textField>
<textField >
<reportElement x="146" y="11" width="100" height="25" /> 
<textFieldExpression class="java.lang.String">
<![CDATA[$F{CITY}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x="263" y="11" width="100" height="24" />
<textFieldExpression class="java.lang.String">
<![CDATA[$F{STATE}]]>
</textFieldExpression>
</textField>
<textField >
<reportElement x="384" y="12" width="100" height="24" /> 
<textFieldExpression class="java.math.BigDecimal">
<![CDATA[$F{QTY_SALES}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>

Brief descriptions of the most important sections for designing a report are given below.

title

As the name implies, this section contains the report title and appears at the top of the report.

queryString

This section defines the SQL query to obtain data for report filling process. This section of the XML template does not contain a height or a width.

pageHeader

This section appears at the top of each page in the report and can be used to display information such as dates, page numbers, etc.

columnHeader

This section is used to display the information as heading for each column.

detail

This is the body of the report. It contains data from the data repository.

columnFooter

This section goes at the bottom of each column and can be used to display information such as the total number of records.

pageFooter

This section appears at the bottom of each page in the report.

Summary

This section contains the information that will be displayed at the end of the report.

Now, let us see how to use JasperReports in Java applications. To create JasperReports report, this JRXML/XML file needs to be loaded. A JasperDesign Object represents the report design. The following codes illustrate this.

Listing 2

JasperDesign jasperDesign = JRXmlLoader.load (
C:/jasperReports/demo.jrxml);
Compiling Report

Now it needs to be compiled into a binary format to produce a report using Java Application. The compileReport() method of the net.sf.jasperreports.engine.JasperCompileManager class is used for this purpose. The compilation process verifies the validity and consistency of the JRXML/XML file using jaspereports.dtd. Whenever a JRXML/XML file is compiled it creates a new file with the extension .jasper called as “Jasper file.” The following code illustrates this.

Listing 3

JasperReport jasperReport = JasperCompileManager
.compileReport(jasperDesign);
Filling Report

net.sf.jasperreports.engine.JasperFillManager class is used for report filling process. This class has various methods that allow us to fill a report design. Every method takes three arguments to fill a report.

·         Compiled Report Design

·         Parameters

·         Datasources

JasperPrint object represents the output, which can be viewed, printed or exported to many different formats.

Listing 4

JasperPrint jasperPrint = JasperFillManager.fillReport
(jasperReport, parameters, conn);

To retrieve data from database, you must have a JDBC connection.

Listing 5

Class.forName("DriverClassName");
Connection conn = DriverManager.getConnection("URL",
"UserName","Password");

The parameters argument is a java.util.HashMap class instance, used to pass values to the report to modify report data at run time. The following syntax is used for this.

Listing 6

Map parameters = new HashMap();
parameters.put ("NameOfParameter", "ValueForParameter");
Exporting Report

A JasperReports report can be exported to a XML, PDF, HTML, XLS file or any other format supported by JasperReports.

To export the JasperReports report into a PDF file, exportReportToPdfStream() method of the net.sf.jasperreports.engine.export.JasperExportManager class is used. The following code accomplishes this.

Listing 7

JasperExportManager.exportReportToPdfFile(jasperPrint,
”C:/jasperRepots/demo.pdf”);

This generates a PDF (here demo.PDF) file, which can be read by Adobe Acrobat Reader as shown in the following figure.

Figure 1

 

 

To export your JasperReports reports into an Excel spreadsheet, use JRXlsExporter object and pass the JasperPrint object from which the report is to be generated and also set the OUTPUT_FILE_NAME to generate the report. The following code generate an Excel (here demo.xls) file.

Listing 8

JRXlsExporter exporterXls = new JRXlsExporter ();
exporterXls.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporterXls.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, 
C:/jasperRepots/demo.xls”);
exporterXls.exportReport();
JasperReports Using Servlet

For creating a JasperReports report using Servlet, you have to create a directory called lib inside WEB-INF and place all the required JAR files inside lib directory.

Listing 9

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.engine.export.*;
 
public class JasperReportServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
ServletOutputStream servletOutputStream = response.getOutputStream();
Connection conn = null;
JasperReport jasperReport;
JasperPrint jasperPrint;
JasperDesign jasperDesign;
try
{
// get a database connection
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection
("jdbc:oracle:thin:@192.168.10.85:1521:oracledb", "xyz","abc");
 
// create a map of parameters to pass to the report.
Map parameters = new HashMap();
parameters.put("Report_Title", "Salesman Details");
 
// load JasperDesign from XML and compile it into JasperReport
jasperDesign = JRXmlLoader.load("C:/jasperReports/demo.jrxml");
jasperReport = JasperCompileManager.compileReport(jasperDesign);
 
// fill JasperPrint using fillReport() method
jasperPrint = JasperFillManager.fillReport(jasperReport,parameters,conn);
 
JasperExportManager.exportReportToPdfFile(jasperPrint,
"C:/jasperReports/demo.pdf");
response.setContentType("application/pdf");
//for creating report in excel format
JRXlsExporter exporterXls = new JRXlsExporter();
exporterXls.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporterXls.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
"C:/jasperReports/demo.xls");
exporterXls.exportReport();
JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
 
servletOutputStream.flush();
servletOutputStream.close();
}
catch(SQLException sqle)
{
 System.err.println(sqle.getMessage());
}
catch (ClassNotFoundException e)
{
 System.err.println("No such class found!");
}
catch (JRException e)
{
// display stack trace in the browser
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
response.setContentType("text/plain");
response.getOutputStream().print(stringWriter.toString());
}
finally
{
//close the connection.
if(conn != null)
{
try { conn.close(); }
catch (Exception ignored) {}
}
}
}
}
Conclusion

This tutorial demonstrated how to generate a report dynamically from database data using JasperReports into PDF and XLS format. Similar techniques can be used to export report into HTML, RTF, CSV file, etc.

 

By Anuva Das
http://www.mindfiresolutions.com

 

 

 

 

 

 

 


Product Spotlight
Product Spotlight 

©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 1:13:56 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search