iReport+jasperReport之scriptlet

阅读更多

           转载自http://www.blogjava.net/bulktree/archive/2008/12/17/246786.html

             提起scriptlet就不能不联想到它的强大功能,jasperReport也是支持scriptlet的哦,先分析一下JasperReport的API吧!
在填充报表时scriplet是一个非常有力的工具,JRAbstractScriptlet.java位于net.sf.jasperreports.engine包下是一个抽象


iReport+jasperReport之scriptlet_第1张图片
beforeReportInit() ,afterReportInit() ,beforePageInit(),afterPageInit(), beforeColumnInit(), afterColumnInit() ,beforeGroupInit(String groupName),afterGroupInit(String groupName) 
看看这些名字就知道你能完成那些功能,这几个方法是要求我们实现的,jasperReport给我们提供了一个实现类JRDefaultScriptlet.java,默认的空实现了上面几个方法,它只是很便利的为我们提供了所需的八个方法的空实现。我们写自己的scriptlet时需要继承JRDefaultScriptlet.java这个类实现自己的相应的功能即可。
 先来看一个简单的例子:
先看看模板文件的处理:iReport+jasperReport之scriptlet_第2张图片
新建时填写的这个类是下面我们要介绍的继承自JRDefaultScriptlet.java类,也就是在模板文件中我们要加上如下代码

scriptletClass="org.bulktree.ireport.scriptlet.ScriptletReportDemo"

完整的模板文件如下:scriptletDemo.jrxml

xml version="1.0" encoding="UTF-8"   ?>

DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd" >
< jasperReport
         
name ="scriptletDemo"
         columnCount
="1"
         printOrder
="Vertical"
         orientation
="Portrait"
         pageWidth
="595"
         pageHeight
="842"
         columnWidth
="535"
         columnSpacing
="0"
         leftMargin
="30"
         rightMargin
="30"
         topMargin
="20"
         bottomMargin
="20"
         whenNoDataType
="NoPages"
         scriptletClass
="org.bulktree.ireport.scriptlet.ScriptletReportDemo"
         isTitleNewPage
="false"
         isSummaryNewPage
="false" >
    
< property  name ="ireport.scriptlethandling"  value ="2"   />
    
< property  name ="ireport.encoding"  value ="UTF-8"   />
    
< import  value ="java.util.*"   />
    
< import  value ="net.sf.jasperreports.engine.*"   />
    
< import  value ="net.sf.jasperreports.engine.data.*"   />

    
< parameter  name ="ReportTitle"  isForPrompting ="true"  class ="java.lang.String" />

        
< background >
            
< band  height ="0"   isSplitAllowed ="true"   >
            
band >
        
background >
        
< title >
            
< band  height ="20"   isSplitAllowed ="true"   >
                
< textField  isStretchWithOverflow ="false"  isBlankWhenNull ="false"  evaluationTime ="Now"  hyperlinkType ="None"   hyperlinkTarget ="Self"   >
                    
< reportElement
                        
mode ="Opaque"
                        x
="193"
                        y
="0"
                        width
="134"
                        height
="18"
                        backcolor
="#FFCC33"
                        key
="textField" />
                    
< box > box >
                    
< textElement  textAlignment ="Center"  verticalAlignment ="Middle" >
                        
< font  pdfFontName ="Helvetica-Bold"  size ="12"  isBold ="true" />
                    
textElement >
                
< textFieldExpression    class ="java.lang.String" > $P{ReportTitle} ]]> textFieldExpression >
                
textField >
            
band >
        
title >
        
< pageHeader >
            
< band  height ="0"   isSplitAllowed ="true"   >
            
band >
        
pageHeader >
        
< columnHeader >
            
< band  height ="0"   isSplitAllowed ="true"   >
            
band >
        
columnHeader >
        
< detail >
            
< band  height ="264"   isSplitAllowed ="true"   >
                
< textField  isStretchWithOverflow ="false"  isBlankWhenNull ="false"  evaluationTime ="Now"  hyperlinkType ="None"   hyperlinkTarget ="Self"   >
                    
< reportElement
                        
x ="85"
                        y
="20"
                        width
="329"
                        height
="61"
                        forecolor
="#FF0099"
                        key
="textField-1" />
                    
< box > box >
                    
< textElement  textAlignment ="Center"  verticalAlignment ="Middle" >
                        
< font  pdfFontName ="Helvetica-Bold"  size ="20"  isBold ="true" />
                    
textElement >
                
< textFieldExpression    class ="java.lang.String" > $P{REPORT_SCRIPTLET}.showInfor() ]]> textFieldExpression >
                
textField >
            
band >
        
detail >
        
< columnFooter >
            
< band  height ="0"   isSplitAllowed ="true"   >
            
band >
        
columnFooter >
        
< pageFooter >
            
< band  height ="0"   isSplitAllowed ="true"   >
            
band >
        
pageFooter >
        
< summary >
            
< band  height ="50"   isSplitAllowed ="true"   >
            
band >
        
summary >
jasperReport >

下来看看怎么实现我们自己的scriplet

ScriptletReportDemo.java

package  org.bulktree.ireport.scriptlet;

import  net.sf.jasperreports.engine.JRDefaultScriptlet;
import  net.sf.jasperreports.engine.JRScriptletException;

/**
 * 
 * 
@author bulktree Email: [email protected]
 * @Nov 26, 2008
 
*/

public   class  ScriptletReportDemo  extends  JRDefaultScriptlet  {

    @Override
    
public void afterColumnInit() throws JRScriptletException {
        System.out.println(
"**************************************afterColumnInit()**************************************");
    }


    @Override
    
public void afterDetailEval() throws JRScriptletException {
        System.out.println(
"**************************************afterDetailEval()**************************************");
    }


    @Override
    
public void afterGroupInit(String groupName) throws JRScriptletException {
        System.out.println(
"**************************************afterDetailEval()**************************************");
    }


    @Override
    
public void afterPageInit() throws JRScriptletException {
        System.out.println(
"**************************************afterPageInit()**************************************");
    }


    @Override
    
public void afterReportInit() throws JRScriptletException {
        System.out.println(
"**************************************afterReportInit() begin**************************************");
        
        String str 
= (String) this.getParameterValue("ReportTitle");
        System.out.println(
"report title=====>>>>"+str);
        
        str 
+= str.subSequence(0, str.length()-2);
        
this.setParameterValue("ReportTitle", str);
        System.out.println(
"**************************************afterReportInit() end**************************************");
    }


    @Override
    
public void beforeColumnInit() throws JRScriptletException {
        System.out.println(
"**************************************beforeColumnInit()**************************************");
    }


    @Override
    
public void beforeDetailEval() throws JRScriptletException {
        System.out.println(
"**************************************beforeDetailEval()**************************************");
    }


    @Override
    
public void beforeGroupInit(String groupName) throws JRScriptletException {
        System.out.println(
"**************************************beforeGroupInit()**************************************");
    }


    @Override
    
public void beforePageInit() throws JRScriptletException {
        System.out.println(
"**************************************beforePageInit()**************************************");
    }


    @Override
    
public void beforeReportInit() throws JRScriptletException {
        System.out.println(
"**************************************beforeReportInit()**************************************");
    }


    
public String showInfor() throws JRScriptletException {
        
return "the is scriptlet scriptlet scriptlet the,sscriptlet report the is ascriptlet report this is a scriptlet report this is a scriptlet report";
    }

    
}

这段代码最后一个方法是我们自己的加的,用来在报表上显示一段文本。我们知道对于一个Field、Parameter、Variable,JasperReport分别采用$F{FieldName}、$P{Parametername}、$V{VariableName}来引用,而如果要引用ScriptletReportDemo.java类的showInfor()返回字符串显示在报表上,看看这个就知道了iReport+jasperReport之scriptlet_第3张图片

在afterReportInit方法中我们把parameter字段取出来前后添上五个*号再set进去
    下来写一个test类测试一下:

package  org.bulktree.ireport.scriptlet;

import  java.io.File;
import  java.io.FileInputStream;
import  java.io.InputStream;
import  java.util.HashMap;

import  net.sf.jasperreports.engine.JREmptyDataSource;
import  net.sf.jasperreports.engine.JasperCompileManager;
import  net.sf.jasperreports.engine.JasperFillManager;
import  net.sf.jasperreports.engine.JasperPrint;
import  net.sf.jasperreports.engine.JasperReport;
import  net.sf.jasperreports.view.JasperViewer;

/**
 * 
 * 
@author bulktree Email: [email protected]
 * @Nov 27, 2008
 
*/

public   class  ScriptletTestMain  {

    
public static void main(String[] args) {
        String path 
= "D:/workspace/scriptletDemo.jrxml";

        File file 
= new File(path);
        InputStream in;
        
try {

            HashMap parameters 
= new HashMap();
            parameters.put(
"ReportTitle""LAOSHULIN");
            in 
= new FileInputStream(file);
            JasperReport jasperReport 
= JasperCompileManager.compileReport(in);
            JasperPrint jasperPrint 
= JasperFillManager.fillReport(jasperReport,
                    parameters, 
new JREmptyDataSource());
            JasperViewer viewer 
= new JasperViewer(jasperPrint);
            viewer.setVisible(
true);

        }
 catch (Exception e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}


效果不错吧:

iReport+jasperReport之scriptlet_第4张图片

getParameterValue、setParameterValue方法可以操作Parameter,Field/Variable该怎么set呢?
    看看 JRAbstractScriptlet.java类的这个方法:

public   void  setData(
        Map parsm,
        Map fldsm,
        Map varsm,
        JRFillGroup[] grps
        )
    
{
        parametersMap 
= parsm;
        fieldsMap 
= fldsm;
        variablesMap 
= varsm;
        groups 
= grps;
    }

        似乎有点意思,我们可以通过这个方法把我们期望的数据组装成Map然后set进去,可是要只针对个别字段怎么处理呢,调用此方法似乎不太合常理,仔细查看API却没有实际能调用的API吧!这个似乎不太合乎,仔细看看确实没有调用的,至少目前我还是没有发现,怎么办 自己写吧!
    设置Field方法:

public   void  setFieldValue(String fieldName, Object value)  throws  JRScriptletException
    
{
        JRFillField field 
= (JRFillField)this.fieldsMap.get(fieldName);
        
if (field == null)
        
{
            
throw new JRScriptletException("FieldName not found : " + fieldName);
        }

        
        field.setValue(value);
    }

    设置Variable方法:

public   void  setVariableValue(String variableName, Object value)  throws  JRScriptletException
    
{
        JRFillVariable variable 
= (JRFillVariable)this.variablesMap.get(variableName);
        
if (variable == null)
        
{
            
throw new JRScriptletException("Variable not found : " + variableName);
        }

        
        
if (value != null && !variable.getValueClass().isInstance(value) )
        
{
            
throw new JRScriptletException("Incompatible value assigned to variable " + variableName + ". Expected " + variable.getValueClassName() + ".");
        }

        
        variable.setValue(value);
    }

    OK!这样我们就可以针对报表上的每一个字段处理了,测试通过 代码就不贴了哦,写上篇的时候忘记这两个方法是我自己加的,查看API时才发现所以来了个续

你可能感兴趣的:(JasperReport,IReport,Scripts)