Ebooks

JasperReports CSV tutorial

JasperReports CSV tutorial shows how to create a report from a CSV data source.

JasperReports is an open-source reporting library. It can create reports in various formats including PDF, HTML, XLS, or CSV. JRCsvDataSource is a datasource implementation that reads a CSV stream.

JasperReports CSV example

The following application creates a report from from a CSV file with JasperReports library. The report is a PDF file.

pom.xml
src
└───main
    ├───java
    │   └───com
    │       └───zetcode
    │           ├───main
    │           │       CommandLineRunner.java
    │           │       JasperCSVDataSource.java
    │           └───model
    │                   Car.java
    └───resources
            cars.csv
            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>csvdatasource</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.9.0</version>
        </dependency>

    </dependencies>

</project>

The Maven pom.xml file contains the jasperreports dependency.

src/resources/cars.csv
1,Audi,52642
2,Mercedes,57127
3,Skoda,9000
4,Volvo,29000
5,Bentley,350000
6,Citroen,21000
7,Hummer,41400
8,Volkswagen,21600
9,BMW,36600

The cars.csv contains the data to be used in our report.

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"
              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>

    <sortField name="Name"/>

    <columnHeader>
        <band height="15">

            <staticText>
                <reportElement x="0" y="0" width="300" height="15"/>
                <textElement />
                <text><![CDATA[]]> </text>
            </staticText>

            <staticText>
                <reportElement x="0" y="0" width="50" height="15"/>
                <textElement />
                <text><![CDATA[Id]]></text>
            </staticText>

            <staticText>
                <reportElement x="80" y="0" width="100" height="15"/>
                <textElement />
                <text><![CDATA[Name]]></text>
            </staticText>

            <staticText>
                <reportElement x="150" y="0" width="100" height="15"/>
                <textElement textAlignment="Center"/>
                <text><![CDATA[Price]]></text>
            </staticText>

        </band>
    </columnHeader>

    <detail>
        <band height="15">

            <textField>
                <reportElement x="0" y="0" width="50" height="15"/>
                <textElement/>
                <textFieldExpression class="java.lang.Long">
                    <![CDATA[$F{Id}]]>
                </textFieldExpression>
            </textField>

            <textField>
                <reportElement x="80" y="0" width="100" height="15"/>
                <textElement textAlignment="Left"/>
                <textFieldExpression>
                    <![CDATA[$F{Name}]]>
                </textFieldExpression>
            </textField>

            <textField>
                <reportElement x="150" y="0" width="100" height="15"/>
                <textElement textAlignment="Right"/>
                <textFieldExpression class="java.lang.Integer">
                    <![CDATA[$F{Price}]]>
                </textFieldExpression>
            </textField>

        </band>
    </detail>

</jasperReport>

This is the report template file. The template contains two bands: columnHeader and detail.

<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>

There are three fields in the template. Fields are mapped to the elements of the data source. In our case, fields are mapped to the CSV column names.

<textField>
    <reportElement x="80" y="0" width="100" height="15"/>
    <textElement textAlignment="Left"/>
    <textFieldExpression>
        <![CDATA[$F{Name}]]>
    </textFieldExpression>
</textField>

A text field is an element that has an associated expression, which is evaluated with every iteration in the data source to obtain the text content. This text field displays the name of the car. A text field in a detail band is evaluated for each record in the data source. Since we have nine records in the CSV file, the text field is evaluated nine times.

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

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.JRCsvDataSource;

import java.util.HashMap;

public class JasperCSVDataSource {

    public void start() throws JRException {

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

        var columnNames = new String[]{"Id", "Name", "Price"};

        var fileName = "src/main/resources/cars.csv";
        var ds = new JRCsvDataSource(fileName);
        ds.setColumnNames(columnNames);

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

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

The JasperCSVDataSource creates a JasperPrint file from the CSV data source. JasperPrint represents a page-oriented document that can be viewed, printed, or exported to other formats. In our case, it is going to exported into PDF file.

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

The XML template file is compiled into a JasperReport. JasperReport is a compiled template ready to be filled with data.

var columnNames = new String[]{"Id", "Name", "Price"};

These are CSV column names. These column names are mapped into report field names.

var ds = new JRCsvDataSource(fileName);
ds.setColumnNames(columnNames);

JRCsvDataSource is a data source implementation that reads data from a CSV file.

var jprint = JasperFillManager.fillReport(report, parameters, ds);

With the JasperFillManager.fillReport() method, we create a JasperPrint object; an object that can be viewed, printed or exported to other formats.

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

The JasperExportManager.exportReportToPdfFile() method transforms the JasperPrint object into a PDF file.

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

public class CommandLineRunner {

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

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

The CommandLineRunner sets up the application.

$ mvn exec:java

We run the application.

In this tutorial, we have created a report with JasperReports library from a CSV file. List all JasperReports tutorials.