简体   繁体   中英

Dynamic columns with jasper reports

I have a CSV/Excel report with 5 fixed columns and I want to add more columns, depending on the input. Each report generation may require different number of columns.

The jrxml approach is done, so my question is - Can I add dynamic columns in jrxml ?

If not, what is the correct way to do it with coding ? example

Note : I prefer not to use Dynamic Jasper library

I think your purpose can be best achieved by using DynamicJasper which creates report design and layout on the fly. This will allow you to custom made report before generating it.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM