JasperReports報表表示式


報表表示式是JasperReports使我們能夠顯示在報表上的資料計算的強大功能。計算出資料不是一個靜態資料,並且不受特別的報表引數或資料源欄位傳遞的資料。報表表示式是由組合報表引數,欄位和靜態資料。預設情況下,Java語言是用於編寫報表的表示式。其他指令碼語言如Groovy指令碼語言,JavaScript或BeanShell指令碼,報表表示式是由JasperReports編譯器支援。

本章將解釋如何報表表示式工作假設他們一直只用Java語言編寫的。在JRXML報表模板,那裡有定義表示式幾個元素,如下所示:

  • <variableExpression>

  • <initialValueExpression>

  • <groupExpression>

  • <printWhenExpression>

  • <imageExpression>

  • <textFieldExpression>

宣告表示式

基本上,所有的報表表示式是可以參考的報表欄位,報表變數和報表引數Java表示式。

欄位參照表示式

使用在表示式中一個報表欄位參考,欄位的名稱必須放在$F{ 和 }字元序列之間,如下圖所示。 

<textfieldexpression>
   $F{Name}
</textfieldexpression>

下面是一段程式碼從我們現有的jrxml檔案,從報表設計 章節中了解:

<textFieldExpression class="java.lang.String">
    <![CDATA[$F{country}]]>
</textFieldExpression>

變數參照表示式

參照在表示式中的變數,我們必須把像在下面的例子中的變數名放在$V {和}之間:

<textfieldexpression>
   "Total height : " + $V{SumOfHeight} + " ft."
</textfieldexpression>

引數參考表達

參照在表示式中的一個引數,該引數的名稱應放在$ P{和}之間,如下面的例子:

<textfieldexpression>
   "ReportTitle : " + $P{Title}
</textfieldexpression>

下面是一段程式碼從現有的jrxml檔案,這用來表示引數在表示式中參照。 

<textField isBlankWhenNull="true" bookmarkLevel="1">
    <reportElement x="0" y="10" width="515" height="30"/>
    <textElement textAlignment="Center">
        <font size="22"/>
    </textElement>
    <textFieldExpression class="java.lang.String">
       <![CDATA[$P{ReportTitle}]]>
    </textFieldExpression>
    <anchorNameExpression>
       <![CDATA["Title"]]>
    </anchorNameExpression>
</textField>
<textField isBlankWhenNull="true">
    <reportElement  x="0" y="40" width="515" height="20"/>
    <textElement textAlignment="Center">
        <font size="10"/>
    </textElement>
    <textFieldExpression class="java.lang.String">
       <![CDATA[$P{Author}]]>
    </textFieldExpression>
</textField>

正如在上面看到,引數,欄位和變數參照,其實是真正的Java物件。從引數,欄位或在報表模板所作的變數宣告知道他們的類,甚至可以在表示式中呼叫的物件參照的方法。

下面的範例演示如何提取並顯示java.lang.String報表欄位的第一個字母 "Name":

<textFieldExpression>
    $F{Name}.substring(0, 1)
</textFieldExpression>

資源包參考表達

參照在表示式中的資源,關鍵要$R{和}之間放像下面的例子:

<textfieldexpression>
   $R{report.title}
</textfieldexpression>

基於執行時提供的語言環境和report.title鍵,報表模板相關的資源包載入。因此,報表標題是從資源包中提取字串值顯示。更多關於國際化可以在國際化一章中找到。

計算器

計算器是JasperReports,其計算表示式和增量變數或資料集在報表填充時間的實體。在編譯過程中,資訊被產生並儲存在由編譯器在編譯報表。在報表,填充時間此資訊用於構建net.sf.jasperreports.engine.fill.JRCalculator類的一個範例。

Java原始檔生成,並通過對飛基於Java的報表編譯器編譯。這個生成的類是JRCalculator子類,並通過將其編譯產生的位元組碼儲存在JasperReport物件的內部。bytcode被載入在報表填充時間和由此產生的類被範例化,以獲得所需的表示式求值計算器物件。

條件表示式

定義變數表示式時,Jasper報表不支援if-else語句。相反,可以使用三元運算子{cond}? {語句1}:{語句2}。可以巢狀這個操作符Java表示式裡面獲得基於多個條件所需的輸出。

在報表條件表示式的範例

讓我們修改現有報告的模板(第報表設計),並增加對country條件表示式。修訂後的報表模板(jasper_report_template.jrxml)如下。將其儲存到 C: oolsjasperreports-5.0.1 est 目錄:

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

<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" pageWidth="595" pageHeight="842" columnWidth="515" leftMargin="40" rightMargin="40" topMargin="50" bottomMargin="50">
<parameter name="ReportTitle" class="java.lang.String"/>
<parameter name="Author" class="java.lang.String"/>
   <queryString>
    <![CDATA[]]>
   </queryString>
   <field name="country" class="java.lang.String">
      <fieldDescription><![CDATA[country]]></fieldDescription>
   </field>
   <field name="name" class="java.lang.String">
      <fieldDescription><![CDATA[name]]></fieldDescription>
   </field>
   <sortField name="country" order="Descending"/>
   <sortField name="name"/>
   <title>
      <band height="70">
         <line>
            <reportElement x="0" y="0" width="515"
            height="1"/>
         </line>
         <textField isBlankWhenNull="true" bookmarkLevel="1">
            <reportElement x="0" y="10" width="515"
            height="30"/>
            <textElement textAlignment="Center">
            <font size="22"/>
            </textElement>
            <textFieldExpression class="java.lang.String">
            <![CDATA[$P{ReportTitle}]]>
            </textFieldExpression>
            <anchorNameExpression><![CDATA["Title"]]>
            </anchorNameExpression>
            </textField>
            <textField isBlankWhenNull="true">
            <reportElement  x="0" y="40" width="515" height="20"/>
            <textElement textAlignment="Center">
                 <font size="10"/>
            </textElement>
            <textFieldExpression class="java.lang.String">
            <![CDATA[$P{Author}]]>
            </textFieldExpression>
            </textField>
      </band>
   </title>
   <columnHeader>
      <band height="23">
         <staticText>
            <reportElement mode="Opaque" x="0" y="3"
            width="535"	height="15"
            backcolor="#70A9A9" />
            <box>
            <bottomPen lineWidth="1.0"
            lineColor="#CCCCCC" />
            </box>
            <textElement />
            <text><![CDATA[]]>
            </text>
         </staticText>
         <staticText>
            <reportElement x="414" y="3" width="121"
            height="15" />
            <textElement textAlignment="Center"
            verticalAlignment="Middle">
               	<font isBold="true" />
            </textElement>
            <text><![CDATA[Country]]></text>
         </staticText>
         <staticText>
            <reportElement x="0" y="3" width="136"
            height="15" />
            <textElement textAlignment="Center"
            verticalAlignment="Middle">
               <font isBold="true" />
            </textElement>
            <text><![CDATA[Name]]></text>
         </staticText>
      </band>
   	</columnHeader>
   	<detail>
      <band height="16">
         <staticText>
            <reportElement mode="Opaque" x="0" y="0"
            width="535"	height="14"
            backcolor="#E5ECF9" />
            <box>
               <bottomPen lineWidth="0.25"
               lineColor="#CCCCCC" />
            </box>
            <textElement />
            <text><![CDATA[]]>
            </text>
         </staticText>
         <textField>
            <reportElement x="414" y="0" width="121"
            height="15" />
            <textElement textAlignment="Center"
            verticalAlignment="Middle">
               <font size="9" />
            </textElement>
            <textFieldExpression class="java.lang.String">
              <![CDATA[$F{country}.isEmpty() ? "NO COUNTRY" : $F{country}]]>
            </textFieldExpression>
         </textField>
         <textField>
            <reportElement x="0" y="0" width="136"
            height="15" />
            <textElement textAlignment="Center"
            verticalAlignment="Middle" />
            <textFieldExpression class="java.lang.String">
            <![CDATA[$F{name}]]>
            </textFieldExpression>
         </textField>
      </band>
   </detail>
</jasperReport>

Java程式碼填充報表如下。該檔案的內容 C: oolsjasperreports-5.0.1 estsrccomyiibaiJasperReportFill.java 如下所述。

package com.yiibai;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class JasperReportFill {
   @SuppressWarnings("unchecked")
   public static void main(String[] args) {
      String sourceFileName =
      "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper";

      DataBeanList DataBeanList = new DataBeanList();
      ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();

      JRBeanCollectionDataSource beanColDataSource =
      new JRBeanCollectionDataSource(dataList);

      Map parameters = new HashMap();
      /**
       * Passing ReportTitle and Author as parameters
       */
      parameters.put("ReportTitle", "List of Contacts");
      parameters.put("Author", "Prepared By Manisha");

      try {
         JasperFillManager.fillReportToFile(
         sourceFileName, parameters, beanColDataSource);
      } catch (JRException e) {
         e.printStackTrace();
      }
   }
}

POJO檔案的內容 C: oolsjasperreports-5.0.1 estsrccomyiibaiDataBean.java 情況如下:

package com.yiibai;

public class DataBean {
   private String name;
   private String country;

   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;
   }
}

將增加country欄位在Java bean列表為空的新紀錄。該檔案的內容C: oolsjasperreports-5.0.1 estsrccomyiibaiDataBeanList.java 情況如下:

package com.yiibai;

import java.util.ArrayList;

public class DataBeanList {
   public ArrayList<DataBean> getDataBeanList() {
      ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();

      dataBeanList.add(produce("Manisha", "India"));
      dataBeanList.add(produce("Dennis Ritchie", "USA"));
      dataBeanList.add(produce("V.Anand", "India"));
      dataBeanList.add(produce("Shrinath", "California"));
      dataBeanList.add(produce("Tanmay", ""));
      return dataBeanList;
   }

   /**
    * This method returns a DataBean object,
    * with name and country set in it.
    */
   private DataBean produce(String name, String country) {
      DataBean dataBean = new DataBean();
      dataBean.setName(name);
      dataBean.setCountry(country);
      return dataBean;
   }
}

報表生成

我們將編譯和執行使用我們常規Ant構建過程上面的檔案。build.xml檔案中的內容(根據目錄儲存:C: oolsjasperreports-5.0.1 est)情況如下。匯入檔案 - 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.yiibai.JasperReportFill (viewFullReport是預設的目標),如下所示:

C:	oolsjasperreports-5.0.1	est>ant -Dmain-class=com.yiibai.JasperReportFill
Buildfile: C:	oolsjasperreports-5.0.1	estuild.xml

clean-sample:
   [delete] Deleting directory C:	oolsjasperreports-5.0.1	estclasses
   [delete] Deleting: C:	oolsjasperreports-5.0.1	estjasper_report_template.jasper
   [delete] Deleting: C:	oolsjasperreports-5.0.1	estjasper_report_template.jrprint

compile:
    [mkdir] Created dir: C:	oolsjasperreports-5.0.1	estclasses
    [javac] C:	oolsjasperreports-5.0.1	estaseBuild.xml:28:
    warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last;
    set to false for repeatable builds
    [javac] Compiling 3 source files to C:	oolsjasperreports-5.0.1	estclasses

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.htmll#noconfig for more info.
      [jrc] File : C:	oolsjasperreports-5.0.1	estjasper_report_template.jrxml ... OK.

run:
     [echo] Runnin class : com.yiibai.JasperReportFill
     [java] log4j:WARN No appenders could be found for logger
     (net.sf.jasperreports.extensions.ExtensionsEnvironment).
     [java] log4j:WARN Please initialize the log4j system properly.

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: 5 minutes 5 seconds

C:	oolsjasperreports-5.0.1	est>

正如上文編譯的結果,JasperViewer視窗開啟如下面的螢幕:

Jasper Report Viewer

在這裡,可以看到,因為沒有通過該欄位country任何資料的最後一條記錄,“NO COUNTRY”正在列印。