1. Introduction

Jaspersoft's Jasper reports are popular in the Java world since they provide us with a simple way to design templates, fill them with data from multiple data sources, and export to many formats - HTML, PDF, DOCX, XLS, XLSX, CSV, ODT, RTF, and ODS. In this short tutorial, we'll be using the Java Beans data source - JRBeanCollectionDataSource and export the Jasper report into .docx format. 

Currently, available Jasper data sources are JDC, JNDI, Hadoop-Hive, AWS, Mongo DB,  Virtual data source that allows us to combine multiple JDBC and/or JNDI data sources into a single data source, Internal diagnostics data source, and finally, Java Bean data source that will be discussed in the following text.

If you need a different file format as an export output, check our tutorials on exporting Jasper Reports to Excel and PDF file types.

Let's see how to create a simple Jasper .docx report and download this report over the REST service using HttpServletResponse. We'll create one simple Java bean with two attributes - name and color. We'll use these parameters to fill our simple report that will have only these two fields and belonging labels.

2. Implementation

We'll create this simple template (complete .jrxml file could be found at the end of this tutorial):

Create Jasper report using Java Bean data source

We'll add this Maven dependency to our pom.xml file: 

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

In this example, we'll create two classes - Java Bean that we'll use as a data source and the second one is an example code where we'll export docx file using our Jasper file and JRBeanCollectionDataSource

The bean class will look like this:

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, let's see how to export the report. We'll do it in Controller for simplicity reasons. 

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.JRDocxExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;

@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("green");
        dataList.add(sampleBean);
        JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
        Map<String, Object> parameters = new HashMap();
        JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName, parameters, beanColDataSource);
        JRDocxExporter exporter = new JRDocxExporter();
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
        response.setHeader("Content-Disposition", "attachment;filename=jasperfile.docx");
        response.setContentType("application/octet-stream");
        exporter.exportReport();
    }
}

4. 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 the code is just for building up the list of beans that will be provided as a data source to JRBeanCollectionDataSource. Even if your report is intended to use only one bean, just create list, add your bean to it and Jasper will do the rest.

// 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, export the report file, and place it into the output stream of HttpServletResponse.

JRDocxExporter exporter = new JRDocxExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
response.setHeader("Content-Disposition", "attachment;filename=jasperfile.docx");
response.setContentType("application/octet-stream");
exporter.exportReport();
    

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

How to use postman to get the report file

JRXML file with a complete code example can be found on GitHub.

5. Conclusion

In this tutorial, we saw how to export .docx file using Jasper reports and download it via REST service in Spring Boot.
Check out our other Jasper Reports tutorials:


You can find a complete project code on GitHub