DynamicJasper is perfect for generating a report having dynamic number of columns.
Here is one code which I used for my N number of columns and M number of rows to create a pdf file by using JRBeanCollectionDataSource.
private List<DynaBean> convertDynaBListFrom2DAry(Object[][] ary2D, int width, int height){
logger.info("Converting report array to dynamic bean as, we have dynamic number of columns");
DynaProperty[] props = new DynaProperty[width];
for (int p=0; p < width; p++) {
DynaProperty dp = new DynaProperty("property"+p);
props[p] = dp;
}
List<DynaBean> dynaBeans = new ArrayList<>(height);
for (Object[] objects : ary2D) {
MutableDynaClass dc = new LazyDynaClass("Row", null, props);
try {
DynaBean row = dc.newInstance();
for (int c=0 ; c < width ; c++ ) {
Object obj = objects[c];
if(obj == null) {
obj = new String("");
}else if(obj.equals("null")) {
obj = new String("");
}else if(obj.equals("NaN")){
obj = new String("");
}
row.set("property"+c, obj);
}
dynaBeans.add(row);
} catch (IllegalAccessException e) {
logger.error("Exception ",e);
} catch (InstantiationException e) {
logger.error("Exception ",e);
}
}
return dynaBeans;
}