JasperReports sorting data

In this tutorial, we show how to sort data in a report created with JasperReports library. Sorting can be accomplished programmatically or by using the sortField tag.

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 in a simple and flexible manner.

Sorting data by field

The following application loads data from a bean collection data source and creates a report from it with JasperReports library. The report is a PDF file.

$ tree
.
├── pom.xml
└── src
    └── main
        ├── java
        │   └── com
        │       └── zetcode
        │           ├── bean
        │           │   └── Car.java
        │           └── main
        │               ├── CommandLineRunner.java
        │               └── JasperSortField2.java
        └── resources
            ├── report2.pdf
            └── report2.xml

This is the project structure.

Car.java
package com.zetcode.bean;

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() {
        return "Car{" + "id=" + id + ", name=" + 
                name + ", price=" + price + '}';
    }
}

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

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>JasperSortField2</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <name>JasperSortField2</name>
    
    <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.

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" pageWidth="595" pageHeight="842" 
   columnWidth="555" leftMargin="20" rightMargin="20"
   topMargin="20" bottomMargin="20">
    
   <style name="textRight" hAlign="Right" vAlign="Middle"/>
  
   <field name="Id" class="java.lang.Long">
      <fieldDescription><![CDATA[id]]></fieldDescription>
   </field>    
    
   <field name="Name" class="java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>
	
   <field name="Price" class="java.lang.Integer">
      <fieldDescription><![CDATA[price]]></fieldDescription>
   </field>
   
   <sortField name="Name" order="Descending"/>  
    <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="150" y="0" width="100" height="15" />
            
            <textElement />
            
            <textFieldExpression class="java.lang.String">
               <![CDATA[$F{Name}]]>
            </textFieldExpression>
         </textField>               
          
         <textField>
            <reportElement x="200" y="0" width="100" height="15" style="textRight" />
            <textElement />
            
            <textFieldExpression class="java.lang.Integer">
               <![CDATA[$F{Price}]]>
            </textFieldExpression>
         </textField>          

      </band>
   </detail>
   
</jasperReport>

This is the report template file. The template contains only the detail band. In a detail band, each element is repeated for every record provided by the data source.

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

The Id field is mapped to the car id attribute.

<sortField name="Name" order="Descending" />  

With the sortField tag, we sort the data by Name field in descending order.

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

  <textElement />

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

The Name field is shown in the textField tag with the $F{} expression.

JasperSortField2.java
package com.zetcode.main;

import com.zetcode.bean.Car;
import java.util.ArrayList;
import java.util.HashMap;
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.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperSortField2 {

    public void start() throws JRException {

        String xmlFile = "src/main/resources/report2.xml";
        JasperReport jreport = JasperCompileManager.compileReport(xmlFile);

        ArrayList<Car> cars = new ArrayList<>();

        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));
        
        JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(cars);

        HashMap params = new HashMap();

        JasperPrint jprint = JasperFillManager.fillReport(jreport,
                params, ds);

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

The JasperSortField2 creates a JasperPrint file from the data source. JasperPrint represents a page-oriented document that can be viewed, printed, or exported to other formats.

String xmlFile = "src/main/resources/report2.xml";
JasperReport jreport = JasperCompileManager.compileReport(xmlFile);

We compile the XML template file into a JasperReport. JasperReport is a compiled template ready to be filled with data.

ArrayList<Car> cars = new ArrayList<>();

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

An ArrayList of cars is our data.

JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(cars);

JRBeanCollectionDataSource is a data source implementation that wraps a collection of Java bean objects. We put four Car beans into the data source.

JasperPrint jprint = JasperFillManager.fillReport(jreport,
        params, ds);

A JasperPrint object is created; an object that can be viewed, printed, or exported to other formats.

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

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

CommandLineRunner.java
package com.zetcode.main;

public class CommandLineRunner {

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

        JasperSortField2 app = new JasperSortField2();
        app.start();
    }
}

The CommandLineRunner sets up the application.

Sorting API

It is possible to sort data in a report with JasperReports' API.

List<JRSortField> sortList = new ArrayList<>();
JRDesignSortField sortField = new JRDesignSortField();
sortField.setName("Price");
sortField.setOrder(SortOrderEnum.ASCENDING);
sortField.setType(SortFieldTypeEnum.FIELD);
sortList.add(sortField);

params.put(JRParameter.SORT_FIELDS, sortList);

The JRDesignSortField is used to sort data.

In this tutorial, we have created a PDF file report with sorted data. You might also be interested in these related tutorials: JasperReports filtering data, JasperReports scriptlets, Creating a report with JasperReports API, Creating a report from CSV with JasperReports, and Java tutorial.