Friday, May 23, 2008

Reporting in Java using JasperReports and iReport

This post is a quick-and-dirty explanation about how to create a reporting application in Java platform.

First, you need to download the iReport. It's an open source graphical report designer for JasperReports. And of course, you must then install it.

Now start the iReport (I use the 1.3.3 version) and create the data source: Data -> Connections/Data Sources. The wizard is intuitive, so you can create it easily. For this example I use "Database JDBC connection" data source type to access MySQL database.

After that, create a new document that will be used as the report: File -> New Document, for now we just need to replace the default name with the desired name, and leave the other properties as it is.

You can now design the report according to your needs. You can add static text, fields (retrieved from the database), etc using components provided in Library window.

To test your report, click Build -> Execute (with active connection) to see the report with the data you've defined in the data source.

Easy right? We will now learn how to call the report from Java application, and for this example I'll use desktop application (using Java Standard Edition).

First, save your report: File -> Save as... (it'll be saved with .jrxml extension). For this example, I give it name News_Report.jrxml.

Use the following code to call the report:

[sourcecode language='java']
import java.sql.*;

import net.sf.jasperreports.view.JasperViewer;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.JasperReport;

public class SimpleReport {

public static void displayReport(String reportFile) {
try{
JasperDesign jasperDesign = JRXmlLoader.load(reportFile);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
Connection jdbcConnection = openConnection();
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, jdbcConnection);
JasperViewer.viewReport(jasperPrint);
}catch(Exception e) {
System.out.println("Error occurred: " + e.getMessage());
}
}

public static void main(String[] args) {
displayReport("News_Report.jrxml");
}
}

[/sourcecode]

No comments:

Post a Comment