如何将任意对象作为参数传递给jasper report?


问题内容

我想将我域的任意对象(例如Person)作为参数传递给.jrxml。

InputStream reportFile = MyPage.this.getClass().getResourceAsStream("test.jrxml");
HashMap<String, Person> parameters = new HashMap<String, Person>();
parameters.put("person", new Person("John", "Doe"));
...
JasperReport report = JasperCompileManager.compileReport(reportFile);
JasperPrint print = JasperFillManager.fillReport(report, parameters, new JREmptyDataSource());
return JasperExportManager.exportReportToPdf(print);

在.jrxml上执行以下操作:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="test" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
 <property name="ireport.zoom" value="1.0"/>
 <property name="ireport.x" value="0"/>
 <property name="ireport.y" value="0"/>
 <parameter name="PERSON" isForPrompting="false" class="myApp.domain.person"/>
 <background>
  <band splitType="Stretch"/>
 </background>
 <title>
  <band height="20">
       <staticText>
         <reportElement x="180" y="0" width="200" height="20"/>
         <text><![CDATA[$P{PERSON.lastName}]]></text>
       </staticText>
     </band>
 </title>
...

这样的事情可能吗?在哪里可以找到更复杂的教程,这些教程不仅显示传递java.lang.String的内容,还显示更多的内容?

谢谢


问题答案:

是的,您可以传递任何Java对象,但应确保将其导入JRXML。

在jasperReport标记内。您可以使用标记import,例如:

 <jasperReport...>
      <import value="org.justfortest.Person">

但是,您可以使用JRBeanCollectionDataSource对象列表来使用该报表并填充该报表,而无需在params映射中存储任意对象。

查看本教程以获取有关Jasper Reports
Bean集合数据源的
更多信息。