1. Introduction

In this tutorial, we'll show how to create a Jasper report with Java and MongoDB. We'll export our report to an MS Excel file. If you want to export your Jasper report to MS Word file, check out this tutorial. In case you need PDF format, check out this one.

We'll create a simple report that shows a list of customers that will be retrieved from our MongoDB collection using a simple Java Spring Boot application. The complete code and template used for this tutorial could be found on GitHub.

2. Implementation

Let's see how to create a Jasper Excel report using Java Beans and JRBeanCollectionDataSource and download this report over the REST service using HttpServletResponse

2.1. Data

First, let's create a collection in the Mongo database that will contain our test customer data.

Create a Jasper report with Java and MongoDB

We'll add four customers that will contain _id, name, and address fields.

2.2. Jasper template

Also, let's create a simple Jasper report template. We're using Jasper Studio for this purpose.

The template is simple, we'll only have three fields in the Detail section and their labels.

Create a Jasper report with Java and MongoDB

2.3. Maven dependencies

Let's add a dependency for Mongo Java driver:

<dependency>
 <groupId>org.mongodb</groupId>
 <artifactId>mongo-java-driver</artifactId>
 <version>3.12.7</version>
</dependency>

And also, for Jasper reports:

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

2.4. Implementation

Let's create a Customer POJO class:

package com.javahowtos.jasperdemo.model;

public class Customer {

	private String id;
	private String name;
	private String address;
	
	public Customer(String id, String name, String address) {
		super();
		this.id = id;
		this.name = name;
		this.address = address;
	}
        
     //getters, setters
}

For simplicity reason, we'll write all code in the Controller class and hard-code the parameters.

@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<Customer> dataList = getCustomerData();
        JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
        Map<String, Object> parameters = new HashMap<String, Object>();
        JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName, parameters, beanColDataSource);
        JRXlsxExporter exporter = new JRXlsxExporter();
        SimpleXlsxReportConfiguration reportConfigXLS = new SimpleXlsxReportConfiguration();
        reportConfigXLS.setSheetNames(new String[] { "Sheet 1" });
        exporter.setConfiguration(reportConfigXLS);
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
        response.setHeader("Content-Disposition", "attachment;filename=jasperfile.xlsx");
        response.setContentType("application/octet-stream");
        exporter.exportReport();
    }
    
    private List<Customer> getCustomerData() throws UnknownHostException {
    	List<Customer> customers = new ArrayList<Customer>();
    	MongoClient mongoClient = new MongoClient(new MongoClientURI("mongodb://localhost:27017"));
    	MongoDatabase database = mongoClient.getDatabase("store");
    	MongoCollection<Document> collection = database.getCollection("customer");
    	MongoCursor<Document> dbCursor = collection.find().iterator();
    	while(dbCursor.hasNext()) {
    		Document object = dbCursor.next();
    		Customer customer = new Customer(object.get("_id").toString(), object.get("name").toString(), object.get("address").toString());
    		customers.add(customer);
    	}
        return customers;
    }
}

2.5. Explanation

The getDocument() method will generate a Jasper report document based on the provided template and data returned from getCustomerData() method. This method uses Mongo Driver to retrieve data from MongoDB collection.

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

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

3. Conclusion

In this tutorial, we learned how to create a Jasper report using Java and MongoDB as a data source. The complete code sample with the Jasper template used for this tutorial is available on GitHub.