Are you using JasperReports?
Do you have a requirement to show columns dynamically based on the user selection?
Or at least - Do you want to know how to add columns dynamically to jasper reports?
If yes, then go ahead and read this....
In general, to generate a report using Jasper - we should have the following:
- The report template (JRXML file) - usually created using a design tool such as iReport.
- The report data - usually created / provided by a datasource provider (DSP). By default Jasper supports several data source providers, but in this blog - we will consider a custom data source provider.
- A DTO (Data Transfer Object) - in effect a java bean with public getters and setters.
- A Java class that compiles the JRXML file, creates the data using the DSP, fills the template with the data.
Generally, we would be defining a set of fields in the JRXML file (apart from variables, parameters). Each such field corresponds/is bound to an attribute / property / member variable in the DTO.
Jasper uses ognl/java reflection to fetch the actual value from the DTO - while filling the report.
Now if we plan to have dynamic columns, let us see what we need to do.
- The number of columns has to be dynamic. The fields (each corresponds to a single column) has to be dynamic => the JRXML file has to be dynamic.
- The fields in JRXML are dynamic => the DTO has to be dynamic.
- The DSP has to be dynamic (basically the place where you create the DTO).
Assume we need to generate a report that would be the amount of .... (yet to write)
Creating a dynamic JRXML file.***
Report design tools such as iReport - provide a GUI interface to create the JRXML file.
But our requirement is to create it on the fly - based on some criteria - such as user selection.
I have used Velocity template to create a JRXML file on the fly.
I have used a JrxmlMetadata bean. The client .... (yet to write)
*** There are other ways to achieve this. You don't need to generate the JRXML. You can directly create a JasperReport Object on the fly - using Java / Jasper Reports API. (When you compile the JRXML file - what you get is a JasperReport Object only). Doing so reduces the dependency on Velocity. But has few drawbacks. Hence I have ignored it :-(
Best Regards,
Madhusudhan.
"Paropakarartham Idham Budhim"
(The very purpose of this mind/knowledge is to help others).