Thursday, July 28, 2016

Dynamic table using Jasper Reports

Today I had to create a dynamic table using jasper reports, where number of columns and rows were not definite. I had to parse a CSV file in java and then using that I had to create a Dynamic table.
So, with the normal table it is not possible in Jasper reports to create dynamic columns/rows , so I used Crosstab for creating dynamic table.
I didn't found much of resource for creating a dynamic table in jasper. so, that's the reason I am writing this.this is the first time I am writing a blog any suggestions are welcomed.

I have used Jasper studio 6.3.0



JAVA PART


First you need to create a Bean:


public class JasperTableModel {

    private Number tableRowData;
    private String columnHeader;
    private Number tablevalues;
 // Getters and Setters...
 // Constructors with fields
}



how to add data in arraylist?

ArrayList<JasperTableModel> tableData = new ArrayList<>();


//first column, first row
tableData.add(new JasperTableModel("rowData1","columnHeader1", "tablevalues11"));

//first column, second row
tableData.add(new JasperTableModel("rowData2","columnHeader1", "tablevalues21"));

//first column, third row
tableData.add(new JasperTableModel("rowData3","columnHeader1", "tablevalues31"));

// Second column, first row
tableData.add(new JasperTableModel("rowData1","columnHeader2", "tablevalues12"));

//Second column, second row
tableData.add(new JasperTableModel("rowData2","columnHeader2", "tablevalues22"));

//Second column, third row
tableData.add(new JasperTableModel("rowData3","columnHeader2", "tablevalues32"));

Creating parameters map  and add 'tableData' arraylist into that map.
Here, I don't have database. so I am using JRBeanCollectionDataSource as a Datasource.

 Map<String, Object> parameters = new HashMap<String, Object>();
 parameters.put("tableDataSource", new JRBeanCollectionDataSource(tableData));


I  am not going to show, how to print that report. I assume, you might have gone through some basic tutorials for jasper reports. and here we are done from Java part.



JASPER REPORTS PART

 Steps:

  1.  Obviously, Create a New report. 
  2.  Create a new parameter 
    1. Name : tableDataSource // it should be same as  parameters passed in java class
    2. Class : net.sf.jasperreports.engine.data.JRBeanCollectionDataSource


   3. Create three new Fields // name should be same name as given in model


 4. Now, we will create Crosstab,
  1. Drag and Drop a crosstab
  2. Use MainDataset
  3. Columns - columnHeader
  4. Rows - tableRowData 
  5. Measures - tablevalues // remember to enter Calculation field carefully, for me it was "No Calculation Function" 
  6. Design as you wish, or simply click Finish
  7. Done. 
  8. compile and run.

 How to remove Total columns/Rows?

Now, By Default crosstab provides Total column.
so If you don't want to have total column ,Change Total position to None;