Search code examples
javajasper-reports

How to get subreport name from JasperReport object (.jasper compiled file) via API?


There's a main report file containing subreports. It is compiled to .jasper and I access it by loading it into JaserReport class.

I am able to get fields and datasets trough

report.getMainDataset().getFields();

However I am unable to get subreports, I've been trying to get them trough the

report.getAllBands();

and then using the for clause

 for (int i = 0; i < bands.length; i++) {
            JRElement[] element = bands[i].getElements(); 
  }

This way I can get some JRBaseSubreport classes, and it is as far as I can get. I can access the elements of subreports, but can't get the names of subreports.

Is there any way to do that?


Solution

  • You can not get data in subreport by only loading the main report into JasperReport object. This object only contains the main report and it's elements.

    The element relative to the subreport is a JRBaseSubreport, which has reference to data relative to subreport tag in main report, hence it does not contain the actual report object.

    The subreport will be loaded by the filler depending on the expressions, you could actually load a different sub report depending on the values of your datasource so jasper report can't know what sub report to load until the report is filled.

    But you can access the expression it will use to load the subreport and this maybe can be enough in your case

    Example on how to access the expression (subreport in first detail band)

    //I know the subreport is in first detail band so I access this directly 
    JRBaseBand detailBand1 = (JRBaseBand) report.getDetailSection().getBands()[0];
    List<JRChild> elements = detailBand1.getChildren(); //Get all children
    for (JRChild child : elements) {
        if (child instanceof JRBaseSubreport){ //This is a subreport
            JRBaseSubreport subreport = (JRBaseSubreport)child;
            String expression= ""; //Lets find out the expression used
            JRExpressionChunk[] chunks = subreport.getExpression().getChunks();
            for (JRExpressionChunk c : chunks) {
                expression +=c.getText();
            }
            System.out.println(expression); 
            //Here you could do code to load the subreport into a JasperReport object
        }
    }
    

    With this data you can load the subreport manually into another JasperReport object and access name, fields etc. Naturally if you have a complex expression your code will need to reflect this (retrive parameters or data from datasource)