Search code examples
javajasper-reports

How to create tree structure in Jasper Report?


I need to display a hierarchical data structure in a report.

Something like this

Sample Table

My data structure is:

class X
{
    List<Y> list;
}

class Y
{
   List<Z> list
}

How is this achieved in jasper report?


Solution

  • Achieving that kind of layout with the datastructure you have showed is normally done by using subreport (or list / table component)

    The structure would be:

    1. Main report, iterate on all x include a subreport 1 for y and z passing the List<Y> list as datasource.

    2. Subreport 1, iterate on all y include a subreport 2 for z passing the List<Z> list as datasource.

    3. Subreport 2, iterate on all z.

    To generate the datasource the JRBeanCollectionDataSource can serve you well example new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($F{list})

    To achieve that rowspan use the stretchType attribute on reportElement (RelativeToBandHeight or RelativeToTallestObject)

    Example

    <textField>
        <reportElement stretchType="RelativeToTallestObject" x="0" y="0" width="100" height="20" uuid="bf6b550c-f37d-4e10-b8dd-1d91c4e6905a"/>
        <textElement verticalAlignment="Middle"/>
            <font size="12"/>
        </textElement>
        <textFieldExpression><![CDATA[$F{x}]]></textFieldExpression>
    </textField>
    

    You don't like subreports, for one level structure the <jr:list> component can be used, see samples