JasperReports创建子报告 JasperReports报告Scriptlets JasperReports创建图表 子报告是JasperReports的一个很好的功能。此功能允许在另一个报表中合并报表,也就是说,一个报表可以是另一个报表的子报表。子报告可以帮助我们简化报表设计,因为我们可以创建许多简单的报表并将它们封装到主报表中。子报表的编译和填充就像普通报告一样。任何报告模板在合并到另一个报告模板时都可以用作子报告,而(报告模板的)内部没有任何更改。 子报表与普通报表模板类似。它们实际上是 net.sf.jasperreports.engine.JasperReport 对象,它们是在编译 net.sf.jasperreports.engine.design.JasperDesign对象 后获得的。 <subreport>元素 将子报表引入主报表时使用<subreport>元素。以下是<subreport> JRXML元素中的子元素列表。 <reportElement> <parametersMapExpression> - 用于将包含报表参数的映射传递给子报表。通常从主报表中的参数获取映射,或者使用内置的REPORTS_PARAMETERS_MAP参数将父报表的参数传递给子报表。此表达式应始终返回一个 java.util.Map 对象,其中键是参数名称。 <subreportParameter> - 此元素用于将参数传递到子报表。它有一个属性 名称 ,这是必需的。 <connectionExpression> - 用于将 java.sql.Connection 传递给子报表。仅在子报表模板在报表填充阶段需要数据库连接时才使用它。 <dataSourceExpression> - 用于将数据源传递到子报表。此数据源通常从主报表中的参数获取,或者使用内置的REPORT_DATA_SOURCE参数将父报表的数据源传递到子报表。 元素( connectionExpression和dataSourceExpression )不能同时出现在<subreport>元素声明中。这是因为我们无法提供数据源和子报表的连接。我们必须决定其中一个并坚持下去。 <returnValue> - 用于将其中一个子报表变量的值分配给主报表的变量之一。此子元素具有以下属性 - subreportVariable - 此属性指定要返回其值的子报表变量的名称。 toVariable - 此属性指定父报表变量的名称,其值将使用子报表中的值进行复制/递增。 计算 - 此属性可以取值:Nothing,Count,DistinctCount,Sum,Average,Lowest,Highest,StandardDeviation,Variance。 属性 计算的 默认值为“Nothing”。 incrementerFactoryClass - 此属性指定用于创建增量器实例的工厂类。 <subreportExpression> - 这表示在何处查找子报表的已编译报表模板。该元素具有 class 属性。在 类 属性可以采取的任何值:java.lang.String中,java.io.File中,java.net.URL中,java.io.InputStream中,net.sf.jasperreports.engine.JasperReport。默认值为 java.lang.String 。 isUsingCache - 这是<subreport>元素的一个属性。这是一个布尔值,当设置为 true时 ,报告引擎将尝试使用其指定的源识别先前加载的子报告模板对象。此缓存功能仅适用于具有表达式的子报表元素,这些表达式将java.lang.String对象作为子报表模板源返回,表示文件名,URL或类路径资源。 例 让我们举一个简单的例子来演示使用JRDataSource创建子报表。让我们先写两个新的报告模板,一个是子报告,另一个是主报告。子报表(address_report_template.jrxml)模板的内容如下所示。将其保存到C:\ tools \ jasperreports-5.0.1 \ test目录。 <?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 = "address_report_template" pageWidth = "175" pageHeight = "842" columnWidth = "175" leftMargin = "0" rightMargin = "0" topMargin = "0" bottomMargin = "0"> <field name = "city" class = "java.lang.String"/> <field name = "street" class = "java.lang.String"/> <background> <band splitType = "Stretch"/> </background> <title> <band height = "20" splitType = "Stretch"> <staticText> <reportElement x = "0" y = "0" width = "100" height = "20"/> <textElement> <font size = "14" isBold = "true"/> </textElement> <text><![CDATA[Addresses]]></text> </staticText> </band> </title> <pageHeader> <band height = "12" splitType = "Stretch"/> </pageHeader> <columnHeader> <band height = "12" splitType = "Stretch"/> </columnHeader> <detail> <band height = "27" splitType = "Stretch"> <textField> <reportElement x = "0" y = "0" width = "120" height = "20"/> <textElement> <font size = "12" isBold = "true"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{city}+" Address:"]]> </textFieldExpression> </textField> <textField isStretchWithOverflow = "true"> <reportElement x = "120" y = "0" width = "435" height = "20"/> <textElement> <font size = "12"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{street}]]> </textFieldExpression> </textField> </band> </detail> <columnFooter> <band height = "8" splitType = "Stretch"/> </columnFooter> <pageFooter> <band height = "11" splitType = "Stretch"/> </pageFooter> <summary> <band height = "9" splitType = "Stretch"/> </summary> </jasperReport> 当我们使用数据源时,我们需要编写相应的POJO文件 SubReportBean.java ,如下所示。将其保存到目录C:\ tools \ jasperreports-5.0.1 \ test \ src \ com \ codingdict - package com.codingdict; public class SubReportBean { private String city; private String street; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } } 在这里,我们声明了两个字段 'city' 和 'street' ,并定义了相应的getter和setter方法。 现在,让我们更新现有的 DataBean 文件。我们将添加一个新的字段 subReportBeanList ,它是一个java.util.List。该字段将保存SubReportBean对象的列表。DataBean文件的内容如下。将其保存到目录C:\ tools \ jasperreports-5.0.1 \ test \ src \ com \ codingdict。 package com.codingdict; import java.util.List; public class DataBean { private String name; private String country; private List<SubReportBean> subReportBeanList; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public List<SubReportBean> getSubReportBeanList() { return subReportBeanList; } public void setSubReportBeanList(List<SubReportBean> subReportBeanList) { this.subReportBeanList = subReportBeanList; } } 我们现在更新文件C:\ tools \ jasperreports-5.0.1 \ test \ src \ com \ codingdict \ DataBeanList.java 。该文件的内容如下 - package com.codingdict; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class DataBeanList { public ArrayList<DataBean> getDataBeanList() { // Create sub report data SubReportBean subBean1 = new SubReportBean(); subBean1.setCity("Mumbai"); subBean1.setStreet("M.G.Road"); SubReportBean subBean2 = new SubReportBean(); subBean2.setCity("New York"); subBean2.setStreet("Park Street"); SubReportBean subBean3 = new SubReportBean(); subBean3.setCity("San Fransisco"); subBean3.setStreet("King Street"); ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>(); // Create master report data dataBeanList.add(produce("Manisha", "India", Arrays.asList(subBean1))); dataBeanList.add(produce("Dennis Ritchie", "USA", Arrays.asList(subBean2))); dataBeanList.add(produce("V.Anand", "India", Arrays.asList(subBean1))); dataBeanList.add(produce("Shrinath", "California", Arrays.asList(subBean3))); return dataBeanList; } /* * This method returns a DataBean object, * with name, country and sub report * bean data set in it. */ private DataBean produce(String name, String country, List<SubReportBean> subBean) { DataBean dataBean = new DataBean(); dataBean.setName(name); dataBean.setCountry(country); dataBean.setSubReportBeanList(subBean); return dataBean; } } 在上面文件中的方法produce()中,我们设置了SubReportBean的列表。 现在,让我们编写一个新的主报告模板(jasper_report_template.jrxml)。将此文件保存到目录 C:\ tools \ jasperreports-5.0.1 \ test 。该文件的内容如下 - <?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 = "jasper_report_template" language = "groovy" pageWidth = "595" pageHeight = "842" columnWidth ="555" leftMargin = "20" rightMargin = "20" topMargin = "20" bottomMargin = "20"> <parameter name = "SUBREPORT_DIR" class = "java.lang.String" isForPrompting = "false"> <defaultValueExpression> <![CDATA["C:\\tools\\jasperreports-5.0.1\\test\\"]]> </defaultValueExpression> </parameter> <field name = "country" class = "java.lang.String"/> <field name = "name" class = "java.lang.String"/> <field name = "subReportBeanList" class = "java.util.List"/> <background> <band splitType = "Stretch"/> </background> <title> <band height = "35" splitType = "Stretch"> <staticText> <reportElement x = "0" y = "0" width = "204" height = "34"/> <textElement> <font size = "26" isBold = "true"/> </textElement> <text><![CDATA[Contact Report]]></text> </staticText> </band> </title> <pageHeader> <band height = "17" splitType = "Stretch"/> </pageHeader> <columnHeader> <band height = "21" splitType = "Stretch"/> </columnHeader> <detail> <band height = "112" splitType = "Stretch"> <staticText> <reportElement x = "0" y = "0" width = "100" height = "20"/> <textElement> <font size = "12" isBold = "true"/> </textElement> <text><![CDATA[Name:]]></text> </staticText> <staticText> <reportElement x = "0" y = "20" width = "100" height = "20"/> <textElement> <font size = "12" isBold = "true"/> </textElement> <text><![CDATA[Country:]]></text> </staticText> <textField> <reportElement x = "104" y = "0" width = "277" height = "20"/> <textElement> <font size = "12"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{name}]]> </textFieldExpression> </textField> <textField> <reportElement x = "104" y = "20" width = "277" height = "20"/> <textElement> <font size = "12"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{country}]]> </textFieldExpression> </textField> <subreport> <reportElement positionType = "Float" x = "335" y = "25" width = "175" height = "20" isRemoveLineWhenBlank = "true" backcolor = "#99ccff"/> <dataSourceExpression> new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource ($F{subReportBeanList}) </dataSourceExpression> <subreportExpression class = "java.lang.String"> <![CDATA[$P{SUBREPORT_DIR} + "address_report_template.jasper"]]> </subreportExpression> </subreport> <line> <reportElement x = "0" y = "50" width = "550" height = "1"/> </line> </band> </detail> <columnFooter> <band height = "19" splitType = "Stretch"/> </columnFooter> <pageFooter> <band height = "18" splitType = "Stretch"/> </pageFooter> <summary> <band height = "14" splitType = "Stretch"/> </summary> </jasperReport> 在上面的模板中,我们定义了一个新参数“SUBREPORT_DIR”,它定义了子报表的路径。我们定义了一个 java.util.List 类型的字段 subReportBeanList , 它对应于DataBean文件中的属性。元素具有子元素<dataSourceExpression>。我们已将列表 subReportBeanList 放在JRBeanCollectionDataSource的实例中。在子元素<subreportExpression/>中,我们给出了子报表名称(AddressReport.jasper)。 现在,让我们编写一个新类 CreateReport 来编译和执行我们的报告模板。文件 C:\ tools \ jasperreports-5.0.1 \ test \ src \ com \ codingdict \ CreateReport.java 的内容如下所示 - package com.codingdict; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; public class CreateReport { public static void main(String[] args) { String masterReportFileName = "C://tools/jasperreports-5.0.1/test" + "/jasper_report_template.jrxml"; String subReportFileName = "C://tools/jasperreports-5.0.1/test" + "/AddressReport.jrxml"; String destFileName = "C://tools/jasperreports-5.0.1/test" + "/jasper_report_template.JRprint"; DataBeanList DataBeanList = new DataBeanList(); ArrayList<DataBean> dataList = DataBeanList.getDataBeanList(); JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList); try { /* Compile the master and sub report */ JasperReport jasperMasterReport = JasperCompileManager .compileReport(masterReportFileName); JasperReport jasperSubReport = JasperCompileManager .compileReport(subReportFileName); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("subreportParameter", jasperSubReport); JasperFillManager.fillReportToFile(jasperMasterReport, destFileName, parameters, beanColDataSource); } catch (JRException e) { e.printStackTrace(); } System.out.println("Done filling!!! ..."); } } 在这里,我们看到我们正在编译主报告模板和子报告模板,并传递主报告(.jasper)文件以进行报告填充。 报告生成 现在,我们所有的文件都准备好了,让我们使用常规的ANT构建过程来编译和执行它们。文件build.xml的内容(保存在目录C:\ tools \ jasperreports-5.0.1 \ test下面)如下所示。 导入文件 - baseBuild.xml是从环境设置一章中选取的,应该与build.xml放在同一目录中。 <?xml version = "1.0" encoding = "UTF-8"?> <project name = "JasperReportTest" default = "viewFillReport" basedir = "."> <import file = "baseBuild.xml" /> <target name = "viewFillReport" depends = "compile,compilereportdesing,run" description = "Launches the report viewer to preview the report stored in the .JRprint file."> <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true"> <arg value = "-F${file.name}.JRprint" /> <classpath refid = "classpath" /> </java> </target> <target name = "compilereportdesing" description = "Compiles the JXML file and produces the .jasper file."> <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask"> <classpath refid = "classpath" /> </taskdef> <jrc destdir = "."> <src> <fileset dir = "."> <include name = "*.jrxml" /> </fileset> </src> <classpath refid = "classpath" /> </jrc> </target> </project> 接下来,让我们打开命令行窗口并转到build.xml所在的目录。最后,执行命令 ant -Dmain-class = com.codingdict.CreateReport (viewFullReport是默认目标),如下所示 - Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml clean-sample: [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes compile: [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning: 'includeantruntime' was not set, defaulting to [javac] Compiling 7 source files to C:\tools\jasperreports-5.0.1\test\classes compilereportdesing: [jrc] Compiling 1 report design files. [jrc] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory). [jrc] log4j:WARN Please initialize the log4j system properly. [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. [jrc] File : C:\tools\jasperreports-5.0.1\test\ jasper_report_template.jrxml ... OK. run: [echo] Runnin class : com.codingdict.CreateReport [java] Compiling Report Design ... [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory). [java] log4j:WARN Please initialize the log4j system properly. [java] Done filling!!! ... viewFillReport: [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. BUILD SUCCESSFUL Total time: 72 minutes 13 seconds 作为上述编译的结果,JasperViewer窗口打开,如下面的屏幕所示 在这里,我们可以看到显示属性Name,Country和Address。 JasperReports报告Scriptlets JasperReports创建图表