How to dynamically show columns in a Jasper Report?

conditional-statements, jasper-reports, java

Solution

You can try the following

Create a `HashMap` and set the required properties in it

Map params = new HashMap();
params.put("DISPLAY_COLUMN_ONE", "Y")

Pass this `params` map to Jasper in the method

`JasperFillManager.fillReport`

In your JRXML, create a parameter corresponding to each property set in the hashmap above:

`<parameter name="DISPLAY_COLUMN_ONE" class="java.lang.String"/>`

Display the columns based on the parameter value

`<printWhenExpression><![CDATA[$P{DISPLAY_COLUMN_ONE}.equals("Y")]]></printWhenExpression>`

Problem

I am generating a Jasper Report, which has 5 fixed columns. The client has requested the ability to select the number of columns at run time. For example if he checks 2 columns from a displayed JTable then there should be 2 columns in Jasper report, if he checks 4 then there should be four columns in jasper report. To try to solve this I am thinking of adding condition in jasper report. If the client selects column A and B I will set that as a parameter in the report and use that to determine whether to display the column. In order to do these, I need to use conditions in the Jasper XML. Where should I set the conditions in the report.

Original source