如何通过JavaBean数据源进行报告

时间:2019-05-29 20:36:39

标签: jasper-reports parameter-passing javabeans

我的报告中有一个硬编码的数据源:

(...)
        <subreport>
            <reportElement x="10" y="10" width="590" height="70" uuid="e98a3620-58d6-47c1-8c93-6ca3d749b31b"/>
            <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource(testdatasource.CustomerInfoDataSource.getCustomerInfo())]]></dataSourceExpression>
            <subreportExpression><![CDATA[$P{SUBREPORT_DIR} + "CustomerData.jasper"]]></subreportExpression>
        </subreport>
(...)

如您所见,数据源是new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource(testdatasource.CustomerInfoDataSource.getCustomerInfo())

我想以此参数化,以便可以将随机方法作为数据源传递给报表。但是,我不确定如何在JRXML文件中创建参数,以及如何在我的代码中将数据源作为参数传递给报表(或传递给JasperPrint对象)。

换句话说,这不起作用:

<parameter name="CUSTOMER_INFO_DATA_SOURCE" class="java.lang.String" isForPrompting="false">
    <defaultValueExpression><![CDATA["new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource(testdatasource.CustomerInfoDataSource.getCustomerInfo())"]]></defaultValueExpression>
</parameter>

我也不知道如何在这里传递参数:

    JRDataSource dataSource = new JRBeanCollectionDataSource(getCustomerInfos(), false);
    JasperPrint jasperPrint = JasperFillManager.fillReport(compiledTemplate, null, dataSource);

方法public static Collection<CustomerInfo> getCustomerInfos()是我要用来提供报告的方法。

解决方案:

我用以下代码解决了它:

<parameter name="customerInfos" class="java.util.List" isForPrompting="false">
    <defaultValueExpression><![CDATA[testdatasource.CustomerInfoDataSource.getCustomerInfo()]]></defaultValueExpression>
</parameter>

defaultValueExpression是可选的。我添加它只是为了在Jaspersoft Studio中填充报告,而不是通过代码填充。

            <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource($P{customerInfos})]]></dataSourceExpression>

在报告生成代码中,我已通过以下方式将List作为参数传递给JasperPrint

    Map<String, Object> params = new HashMap<>();
    params.put("customerInfos", getCustomerInfos());

    JasperPrint jasperPrint = JasperFillManager.fillReport(compiledTemplate, params, dataSource);

0 个答案:

没有答案
相关问题