繁体   English   中英

将参数传递给Jasper报告的问题

[英]Issue with passing parameter to Jasper reports

我定义了以下模板:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport
        PUBLIC "-//JasperReports//DTD Report Design//EN"
        "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport name="HelloJasper_report">
    <parameter name="customer" class="com.eternity.model.Customer"/>
    <detail>
        <band height="20">
            <staticText>
                <reportElement x="220" y="0" width="200" height="20"/>
                <text><![CDATA[$P{customer.firstName}]]></text>
            </staticText>
        </band>
    </detail>
</jasperReport>

我用以下内容创建报告:

try{
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("customer", new Customer("Example name"));

    System.out.println("Generating PDF...");
    JasperReport jasperReport =
            JasperCompileManager.compileReport("hellojasper.jrxml");
    JasperPrint jasperPrint =
            JasperFillManager.fillReport(jasperReport, parameters, new JREmptyDataSource());
    JasperExportManager.exportReportToPdfFile(
            jasperPrint, "HelloJasper.pdf");

    System.out.println("HelloJasper.pdf has been generated!");
}
catch (JRException e){
    e.printStackTrace();
}

客户在哪里

public class Customer{

    private String firstName;

    public Customer(String firstName){
        this.firstName = firstName;
   }

}

但是,生成的PDF仅打印:

$P{customer.firstName}

我想念什么?

首先,在您的报告中,您声明了一个staticText块,该块将精确打印text标签中的值-这就是为什么您获得$P{person.firstName}

为了评估参数并打印其值,您应该在报表设计中使用textFieldtextFieldExpression

<textField isBlankWhenNull = "true">
    <reportElement x="220" y="0" width="200" height="20"/>
    <textElement/>
    <textFieldExpression class = "java.lang.String">
        <![CDATA[$P{person}.firstName]]>
    </textFieldExpression>
</textField>

其次,您声明了person参数为com.eternity.model.Person类的实例。 尽管在代码中您将Customer作为person参数(并且它似乎不是Person的子类)。 你必须:

  1. 要么使您的Customer成为com.eternity.model.Person的子类,
  2. 或将您的报表设计person参数更改为具有完全合格的软件包名称的Customer类(原始答案中没有可见的软件包)。

最后: firstName字段具有private修饰符,因此您应该在类中添加一个公共的getFirstName方法

public String getFirstName() {
    return this.firstName;
}

然后在报告中调用<![CDATA[$P{person}.getFirstName()]]>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM