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 rowCreating parameters map and add 'tableData' arraylist into that map.
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"));
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:
- Obviously, Create a New report.
- Create a new parameter
- Name : tableDataSource // it should be same as parameters passed in java class
- 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,
- Drag and Drop a crosstab
- Use MainDataset
- Columns - columnHeader
- Rows - tableRowData
- Measures - tablevalues // remember to enter Calculation field carefully, for me it was "No Calculation Function"
- Design as you wish, or simply click Finish
- Done.
- 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;