Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send datasource to subreport?

I work at a report that need a subreport, so I want to pass datasource from a Java method to subreport, but I don't arrive at the correct way. Usually I use the followin piece of code to create my report. What is the correct way to send datasource to subreport?

Map<String, Object> param = new HashMap<>();
param.put("rapportNom", "Module");
param.put("PAR_IMAGE_BACKGROUND", "/dz/suivi/reporting/sources/BackgroundElit.png");
param.put("PAR_IMAGE_HEADER", "/dz/suivi/reporting/sources/headerElit.png");
param.put("SUBREPORT_DIR", "/dz/suivi/reporting/sources/moduleAllDetail_subreport1.jasper");
param.put("SUBREPORT_DATA", "LIST OF OBJECT");

return Reporting.printEtat(getClass().getResourceAsStream("/dz/suivi/reporting/sources/moduleAllDetail.jasper"),
                param, new JRBeanCollectionDataSource(reportingModuleViewFacade.findById(module)));
like image 449
YCF_L Avatar asked Jan 06 '23 03:01

YCF_L


2 Answers

If you have your datasource as a List<MyBean> as simple method is:

  1. Pass it in the parameter map

    param.put("SUBREPORT_DATA", myBeanList);
    
  2. Define the parameter in jrxml

    <parameter name="SUBREPORT_DATA" class="java.util.List"/>
    
  3. Create a JRBeanCollectionDataSource using your parameter

    <subreport>
        <reportElement x="0" y="0" width="200" height="100" uuid="406c9014-e74b-42d9-b9e1-4af106bfb779"/>
        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{SUBREPORT_DATA})]]></dataSourceExpression>
        <subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "theSubreport.jasper"]]></subreportExpression>
    </subreport>
    
like image 122
Petter Friberg Avatar answered Jan 17 '23 20:01

Petter Friberg


I wrote an article for programming and configuring jasperreport with report, subreport and datasources:

For subreport:

When attaching a subreport to the master report, it’s important to set the Expression and the Data Source expression properties;

Expression property is used to find out which report to use, while the Data Source is the data attached on the subreport.

While Expression can be set to the relative path of the subreport .jasper (ex. “report/subreport.jasper”), it is also possible to load the compiled jasper from another source like an input stream.

For this purpose, create a parameter in the master report (in this case called PersonsSubReport) and set the Expression property to $P{PersonsSubReport}.

In this way it’s possible to inject the subreport from the code on the fill and build process. (We’ll see it later)

Set Data Source expression to:

new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{persons})
like image 37
Fabrizio Stellato Avatar answered Jan 17 '23 20:01

Fabrizio Stellato