Of course! Here is a comprehensive guide to using JasperReports with Java, covering everything from the basic concepts to a practical, step-by-step example.

What is JasperReports?
JasperReports is an open-source Java library for creating dynamic, pixel-perfect reports. It's one of the most popular reporting tools in the Java ecosystem. You define the layout of your report (the "how it looks") in an XML file (.jrxml), and then you supply it with data (the "what to show") from your Java application. The library then merges the two to generate the final report in various formats like PDF, HTML, Excel, etc.
Key Features:
- Multiple Output Formats: PDF, HTML, XLS, CSV, XML, RTF, ODT, and more.
- Rich Data Sources: Works with JavaBeans, Collections, Maps, JDBC, and NoSQL databases.
- Subreports: Allows you to nest one report inside another for complex layouts.
- Charts and Graphics: Built-in support for charts, barcodes, and custom drawing.
- Scriptlets: Allows you to write custom Java code to handle complex logic within the report.
- Templates: Master reports and templates for consistent styling.
Core Concepts
Before diving into the code, it's essential to understand the main components involved in generating a report.
-
.jrxmlFile (Report Template): This is an XML file that defines the structure and layout of your report. It contains elements like:
(图片来源网络,侵删)parameters: Input values passed to the report (e.g., a title, a date).fields: Data fields that come from your data source (e.g.,product.name,customer.address).- `variables**: Calculated values within the report (e.g., a page count, a total sum).
title,pageHeader,columnHeader,detail,columnFooter,pageFooter,summary: Report sections.
-
JasperReportObject (Compiled Template): The.jrxmlfile must be compiled into a binary format (.jasper) using theJasperCompileManager. This.jasperfile is a serialized Java object that the engine can use much faster than parsing the XML every time. -
DataSource(Data Source): This is the object that provides the actual data for the report. JasperReports is very flexible and can use various types of data sources:JRBeanCollectionDataSource: Ajava.util.Collectionof JavaBeans.JRMapCollectionDataSource: Ajava.util.Collectionofjava.util.Mapobjects.JREmptyDataSource: For reports with no data (e.g., a cover page).JRResultSetDataSource: A JDBCResultSet.
-
JasperFillManager(Filling Process): This is the core engine that takes the compiled.jasperfile, the data source, and parameters to "fill" the template with data, producing aJasperPrintobject. -
JasperPrintObject (Filled Report): This is an in-memory representation of the final, filled report. It's not yet in a specific output format. It contains all the data, bands, and formatting ready to be exported.
(图片来源网络,侵删) -
JasperExportManager(Exporting): This utility class takes theJasperPrintobject and exports it to your desired format (PDF, HTML, etc.).
Step-by-Step Example: Generating a PDF Report
Let's create a simple report that lists a few products. We'll use Maven for dependency management.
Step 1: Set Up Your Maven Project (pom.xml)
Add the JasperReports dependency. It's a good practice to use the latest stable version.
<dependencies>
<!-- JasperReports Core Library -->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.21.3</version> <!-- Check for the latest version -->
</dependency>
</dependencies>
Step 2: Create the Data Source (JavaBean)
Create a simple Java class to represent our data.
Product.java
public class Product {
private Integer id;
private String name;
private Double price;
public Product(Integer id, String name, Double price) {
this.id = id;
this.name = name;
this.price = price;
}
// Getters are required for JasperReports to access the fields
public Integer getId() { return id; }
public String getName() { return name; }
public Double getPrice() { return price; }
}
Step 3: Create the Report Template (ProductReport.jrxml)
Create a file named ProductReport.jrxml in your project's src/main/resources directory. This XML file defines the report layout.
<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.20.6.final using JasperReports Library version 6.20.6 -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="ProductReport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<!-- Title of the report -->
<band height="70">
<staticText>
<reportElement x="180" y="20" width="200" height="30"/>
<textElement textAlignment="Center">
<font size="18" isBold="true"/>
</textElement>
<text>Product List Report</text>
</staticText>
</band>
<!-- Column Header (header for the data columns) -->
<columnHeader>
<band height="30">
<staticText>
<reportElement x="0" y="0" width="100" height="30"/>
<textElement textAlignment="Center">
<font isBold="true"/>
</textElement>
<text>ID</text>
</staticText>
<staticText>
<reportElement x="100" y="0" width="255" height="30"/>
<textElement textAlignment="Center">
<font isBold="true"/>
</textElement>
<text>Name</text>
</staticText>
<staticText>
<reportElement x="355" y="0" width="200" height="30"/>
<textElement textAlignment="Center">
<font isBold="true"/>
</textElement>
<text>Price</text>
</staticText>
</band>
</columnHeader>
<!-- Detail Section (where the data is printed) -->
<detail>
<band height="30">
<!-- This field will be populated with the 'id' from our Product object -->
<textField>
<reportElement x="0" y="0" width="100" height="30"/>
<textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
</textField>
<!-- This field will be populated with the 'name' from our Product object -->
<textField>
<reportElement x="100" y="0" width="255" height="30"/>
<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
</textField>
<!-- This field will be populated with the 'price' from our Product object -->
<textField>
<reportElement x="355" y="0" width="200" height="30"/>
<textFieldExpression><![CDATA[$F{price}]]></textFieldExpression>
</textField>
</band>
</detail>
<!-- Summary Section (e.g., for a total) -->
<summary>
<band height="50">
<staticText>
<reportElement x="180" y="10" width="200" height="30"/>
<textElement textAlignment="Center">
<font size="14" isBold="true"/>
</textElement>
<text>End of Report</text>
</staticText>
</band>
</summary>
</jasperReport>
Explanation of JRXML Syntax:
$F{fieldName}: This is the syntax for referencing a field from your data source. The field name must match the getter name in your JavaBean (e.g.,$F{id}maps toproduct.getId()).$P{parameterName}: Syntax for referencing a parameter.$V{variableName}: Syntax for referencing a variable.
