Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

Generate Jasper report with subreport from java

I know how to generate jasper report without any subreport. But currently I have a subreport in my report and I would like to know how can I compile that subreport in java?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can compile the subreport like the simple report - with help of JasperCompileManager.compileReport(java.lang.String sourceFileName) method, for example.

After that you can pass the compiled subreport as parameter to the master report.

The sample:

JasperReport jasperMasterReport = JasperCompileManager.compileReport(masterReportSource);
JasperReport jasperSubReport = JasperCompileManager.compileReport(subReportSource);

Map<String, Object> parameters = new HashMap()<String, Object>;
parameters.put("subreportParameter", jasperSubReport);

JasperFillManager.fillReportToFile(jasperMasterReport, parameters, outputFileName, connection);

The snippet from the master report's jrxml file (sample):

<parameter name="subreportParameter" class="net.sf.jasperreports.engine.JasperReport"/>
...
<detail>
    <band height="50">
        ...
        <subreport>
                <reportElement isPrintRepeatedValues="false" x="5" y="25" width="325" height="20" isRemoveLineWhenBlank="true" backcolor="#ffcc99"/>
                <subreportParameter name="City">
                    <subreportParameterExpression><![CDATA[$F{City}]]></subreportParameterExpression>
                </subreportParameter>
                <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                <returnValue subreportVariable="PriceSum" toVariable="ProductTotalPrice" calculation="Sum"/>
                <subreportExpression class="net.sf.jasperreports.engine.JasperReport"><![CDATA[$P{subreportParameter}]]></subreportExpression>
            </subreport>

Notes

I mentioned an old API for generating result: JasperFillManager.fillReportToFile(JasperReport, String, Map, java.sql.Connection)

In case using JasperReports 6.x it is better to use exporters (concrete implementation of net.sf.jasperreports.export.Exporter interface, for example JRPdfExporter) for generating output file

The example how to use Exporter right can be found here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...