Variable amount of sub-reports in jasper

JasperReports is pretty straightforward when working with sub-reports. But you may need to display multiple different tables within a single report but without knowing how many tables will be needed in the final report. In this case, you need to have a dynamic mechanism. In the following example, a report with  a random amount of tables will be created.

The sub-report

In this example, we have a report consisting of multiple tables. As we will provide each sub-report its own data source and parameter map, we do not have to mind anything special. First, we need a container which holds the data for each row.

The following example will generate a table with a title, a column header and rows depending on the data source.

We’ll use a simple function in order to build the data source for the table we generate above.

Referencing the sub-report

We will use the detail section of the jasper report in order to support multiple different sub-reports. Usually there are three parameters required for each sub-report:

  • The parameter map
  • The data source (remember to always use a different data source for each sub report, otherwise you’ll have a mess)
  • The report itself (it’s also possible to reference the actual file)

For this set, we create first create a POJO which holds this information.

With this simple container, we create a data source which can be used when generating the actual report.

Now we have to reference these reports within the parent report. To do so, we simply add the sub report to the detail section and reference the fields of the previously created POJO.

Creating the report

Now, as we have fully created our environment to create a report with a variable amount of sub-reports, we simply need to fire up the generation process.

Example Code


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.