Introduction

Jaspersoft's Jasper reports are popular in Java world since they offer a simple way to design templates and export data into many formats - HTML, PDF, DOCX, XLS, XLSX, CSV, ODT, RTF and ODS.

In this simple tutorial, we'll show how to create a Jasper Excel xlsx report using Java Beans and JRBeanCollectionDataSource and download this report over the REST service using HttpServletResponse. We'll create one simple bean with two attributes - name and color and use it to fill our basic report that will have only these two fields and belonging labels.

Implementation

Our design will look like this (complete .jrxml file could be found at the end of this tutorial):

Create and download Jasper report xlsx via REST service in Spring Boot

Dependencies

Let's add Jasper Reports Maven dependency to your pom.xml: 

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

Implementation

In this example, we'll have two classes - first is Java Bean that we'll use as a data source and the second one is an example code where we'll create xlsx file using our Jasper file and provided data source. 

So, this would be the bean class - it contains only fields and getters and setters.

public class SampleBean {
	
String name;
String color;

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

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}
}

And this is the exporter class.

package com.javahowtos.jasperdemo.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javahowtos.jasperdemo.beans.SampleBean;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;

@RestController
@RequestMapping("api/document")
public class JasperDemoController {

    @GetMapping()
    public void getDocument(HttpServletResponse response) throws IOException, JRException {

        String sourceFileName = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "SampleJasperReport.jasper")
            .getAbsolutePath();
        List<SampleBean> dataList = new ArrayList<SampleBean>();
        SampleBean sampleBean = new SampleBean();
        sampleBean.setName("some name");
        sampleBean.setColor("red");
        dataList.add(sampleBean);
        JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
        Map<String, Object> parameters = new HashMap();
        JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName, parameters, beanColDataSource);
        JRXlsxExporter exporter = new JRXlsxExporter();
        SimpleXlsxReportConfiguration reportConfigXLS = new SimpleXlsxReportConfiguration();
        reportConfigXLS.setSheetNames(new String[] { "sheet1" });
        exporter.setConfiguration(reportConfigXLS);
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
        response.setHeader("Content-Disposition", "attachment;filename=jasperReport.xlsx");
        response.setContentType("application/octet-stream");
        exporter.exportReport();
    }
}

Explanation 

We'll need the location of our .jasper file that is placed in the resources folder of our Maven project, so we'll use ResourceUtils to get to the files' absolute path.

String sourceFileName = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "SampleJasperTemplate.jasper").getAbsolutePath();

The following part of code is just for building up the list of beans that will be provided as a data source to JRBeanCollectionDataSource. In case you don't want to pass a list of objects, but the only one instead, create it and add it to the list, Jasper will know how to deal with it. 

// creating our list of beans
List<SampleBean> dataList = new ArrayList<SampleBean>();
SampleBean sampleBean = new SampleBean();
sampleBean.setName("some name");
sampleBean.setColor("red");
dataList.add(sampleBean);
// creating datasource from bean list
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);

The parameter Map is used for providing the report with some extra parameters. We currently don't need that, so we'll just pass the empty one.

JasperPrint object we create in the following line will be later used to fill the report that will be written to HttpServletResponse's output stream:

Map<String, Object> parameters = new HashMap();
JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName, parameters, beanColDataSource);

The following code is used for creating the exporter. Class SmpleXlsxReportConfiguration is used to configure resulting .xlsx file. In this example, we'll set the sheet name.

  JRXlsxExporter exporter = new JRXlsxExporter();
        SimpleXlsxReportConfiguration reportConfigXLS = new SimpleXlsxReportConfiguration();
        reportConfigXLS.setSheetNames(new String[] { "sheet1" });
        exporter.setConfiguration(reportConfigXLS);
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
        response.setHeader("Content-Disposition", "attachment;filename=jasperReport.xlsx");
        response.setContentType("application/octet-stream");
        exporter.exportReport();

It's important to give the resulting file the name and type so the browser can handle it easily (if you're using Postman to test this, click Send and Download instead just Send).

Create and download Jasper report xlsx via REST service in Spring Boot

A complete example with JRXML can be found on GitHub.

Conclusion

In this tutorial, we saw how to export xlsx file using Jasper reports and download it via REST service in Spring Boot. You can find a complete list of dependencies in the full project on GitHub