Ebooks

JasperReports noData tutorial

JasperReports noData tutorial shows how to generate report when no data is available.

JasperReports is an open-source reporting library. It can create reports in various formats including PDF, HTML, XLS, or CSV. JasperReports creates page-oriented, ready-to-print documents.

JasperReports noData section

The noData section can be used in a report when the datasource is empty. When there is no data, JasperReports generates a blank page. To generate the noData section with empty datasource, we define the section in the report and set the whenNoDataType of the jasperReport tag to NoDataSection. (The default is BlankPage).

JasperReports noData example

The following application generates the noData section when there is an empty datasource.

pom.xml
src
└───main
    ├───java
    │   └───com
    │       └───zetcode
    │           ├───main
    │           │       CommandLineRunner.java
    │           │       JasperNodata.java
    │           └───model
    │                   Car.java
    └───resources
            report2.xml

This is the project structure.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>nodata</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <exec.mainClass>com.zetcode.main.CommandLineRunner</exec.mainClass>
    </properties>

    <dependencies>

        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.4.0</version>
        </dependency>

    </dependencies>

</project>

The Maven pom.xml file contains the jasperreports dependency.

com/zetcode/model/Car.java
package com.zetcode.model;

public class Car {

    private Long id;
    private String name;
    private int price;

    public Car() {}

    public Car(Long id, String name, int price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("Car{");
        sb.append("id=").append(id);
        sb.append(", name='").append(name).append('\'');
        sb.append(", price=").append(price);
        sb.append('}');
        return sb.toString();
    }
}

This is Car bean class. It contains car id, car name, and car price attributes.

src/resources/report2.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN"
        "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<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"
              whenNoDataType="NoDataSection"
              name="report2" topMargin="20" bottomMargin="20">

    <field name="Id" class="java.lang.Long">
        <fieldDescription><![CDATA[id]]></fieldDescription>
    </field>

    <field name="Name">
        <fieldDescription><![CDATA[name]]></fieldDescription>
    </field>

    <field name="Price" class="java.lang.Integer">
        <fieldDescription><![CDATA[price]]></fieldDescription>
    </field>

    <detail>
        <band height="15">

            <textField>
                <reportElement x="0" y="0" width="50" height="15"/>

                <textElement textAlignment="Right" verticalAlignment="Middle"/>

                <textFieldExpression class="java.lang.Long">
                    <![CDATA[$F{Id}]]>
                </textFieldExpression>
            </textField>

            <textField>
                <reportElement x="150" y="0" width="100" height="15" />

                <textElement textAlignment="Left" verticalAlignment="Middle"/>

                <textFieldExpression class="java.lang.String">
                    <![CDATA[$F{Name}]]>
                </textFieldExpression>
            </textField>

            <textField>
                <reportElement x="200" y="0" width="100" height="15" />
                <textElement textAlignment="Right" verticalAlignment="Middle"/>

                <textFieldExpression class="java.lang.Integer">
                    <![CDATA[$F{Price}]]>
                </textFieldExpression>
            </textField>

        </band>
    </detail>

    <noData>
        <band height="15">
            <staticText>
                <reportElement x="0" y="0" width="200" height="15"/>
                <box>
                    <bottomPen lineWidth="1.0" lineColor="#CCCCCC"/>
                </box>
                <textElement />
                <text><![CDATA[The report has no data]]></text>
            </staticText>
        </band>
    </noData>

</jasperReport>

This is the report template file. The template contains the detail band and the noData band. The former is generated when there is some data, the latter when there is no data.

<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"
    whenNoDataType="NoDataSection"
    name="report2" topMargin="20" bottomMargin="20">

The whenNoDataType attribute is set to NoDataSection. By default, the attribute is set to blankPage.

<noData>
    <band height="15">
        <staticText>
            <reportElement x="0" y="0" width="200" height="15"/>
            <box>
                <bottomPen lineWidth="1.0" lineColor="#CCCCCC"/>
            </box>
            <textElement />
            <text><![CDATA[The report has no data]]></text>
        </staticText>
    </band>
</noData>

The noData contains a static text that is displayed in case there is no data. The static text says: The report has no data.

com/zetcode/main/JasperNodata.java
package com.zetcode.main;

import com.zetcode.model.Car;
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.data.JRBeanCollectionDataSource;

import java.util.ArrayList;
import java.util.HashMap;

public class JasperNodata {

    public void start() throws JRException {

        var xmlFile = "src/main/resources/report2.xml";
        var jasperReport = JasperCompileManager.compileReport(xmlFile);

        var cars = new ArrayList<Car>();

        cars.add(new Car(1L, "Audi", 52642));
        cars.add(new Car(2L, "Mercedes", 57127));
        cars.add(new Car(3L, "Skoda", 9000));
        cars.add(new Car(4L, "Volvo", 29000));
        cars.add(new Car(5L, "Bentley", 350000));
        cars.add(new Car(6L, "Citroen", 21000));
        cars.add(new Car(7L, "Hummer", 41400));
        cars.add(new Car(8L, "Volkswagen", 21600));

        var empty = new ArrayList<Car>();

        var ds = new JRBeanCollectionDataSource(empty);
        var params = new HashMap<String, Object>();
        var jasperPrint = JasperFillManager.fillReport(jasperReport, params, ds);

        JasperExportManager.exportReportToPdfFile(jasperPrint,
                "src/main/resources/report2.pdf");
    }
}

We have two Java list coitainers; one of them is empty. Depending on which container we pass to the JRBeanCollectionDataSource, the report either generates data from the detail band or the message The report has no data.

com/zetcode/main/CommandLineRunner.java
package com.zetcode.main;

public class CommandLineRunner {

    public static void main(String[] args) throws Exception {

        var app = new JasperNodata();
        app.start();
    }
}

The CommandLineRunner sets up the application.

$ mvn exec:java

We run the application.

In this tutorial, we have created a sum variable to calculate the sum of car prices. List JasperReports tutorials.