1. 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 and in this simple tutorial, we'll be dealing with MS Office Word and export Jasper report into .docx format.

Let's see how to create a simple Jasper .docx 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.

2. Implementation

We'll create the simplest template that will look like this (complete .jrxml file could be found at the end of this tutorial):

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

3. Dependencies

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>

Implementation

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

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

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 list of dependencies in the full project on GitHub