Jasperreport+ireport 实践操作及web应用

Jasperreport+ireport 实践操作及web应用
 
学习完jasperreports+ireport,给我感觉深刻,不仅掌握了报表开发技术,还掌握了怎样在web中生成pdf,xls,rtf文件,下面是jasperreports+ireport开发知识点:
1.字段,变量,參数,传參
2.矢量图,位图
3.超链接,锚
4.数据源,自己定义数据源
5.国际化(I18N)
6.脚本
7.子报表
8.图表(饼图,柱图,线图)
9.导出pdf,xls,html...

操作版本号:jasperreports2.0.2+ireport2.0.2
说明:本文并不是入门级教程,所以阅读本文须要有一定基础.
下面针对每一个知识点,解说在ireport中是怎样操作,以及在真实项目中怎样部署.
1.字段,变量,參数,传參
这个知识点非常easy,在ireport的 view 菜单下有 Fields,Variables,Parameters三个菜单,如要定义一个參数,可进行例如以下操作.
点击 Parameters 菜单,此时弹出一个操作參数的窗体,单击 New button,输入參数名(Parameter Name),选择參数类型(Parameter Class Type),如要赋一个默认值则填写默认值表达式(Default Value Expression)(默认值如为字符串则以"string"形式填写,如为整形则以 new Integer(1) 形式填写,以此类推.),填好后,点 OK 就新建了一个參数了.

定义字段与定义參数是一样的操作,至于定义变量操作差点儿相同,也相对少用一些,在此就不讲述.

在ireport中怎样引用字段,变量,參数?
引用字段使用 $F{field_name}
引用变量使用 $V{variable_name}
引用參数使用 $P{param_name}  或 $P!{param_name}
$P!{param_name}一般用于拼接sql语句,它的值能够与sql语句拼接后,再去运行查询.
例:定义一个參数名为 where 类型为String 默认值为 "where id=100"
有一查询语句:select * from user $P!{where}
则运行查询时会替换成:select * from user where id=100

$P{param_name}在sql语句中使用时,也有一特殊情况.
例:有一參数名为 id,类型为Integer,默认值为 new Integer(100)
有一查询语句:select * from user where id=$P{id}
运行查询可正常查询,但假设有一參数名为 name,类型为String,默认值为"zhanngle"
有一查询语句:select * from user where name=$P{name}
运行查询时出错,不知道为什么(即使数据库中有该条记录),不知是不是bug,还是自已哪里弄错了.解决的方法是,将查询语句改为:select * from user where name='$P!{name}'
能够证明$P!{}语法,仅仅做替换操作,如上仅仅将$P!{name}替换成zhanngle.
也能够证明$P{}语法,在sql语句中使用时,值为数字类型还能够正常运行,如为字符串类型则会出错.

在程序中怎样传參?


如上例定义了一个name參数,那么在程序中怎样动态传參查询出不同的记录呢,也非常easy.
程序代码例如以下:

Map params=new HashMap();
params.put(
"name","zhanngle");
JasperPrint print
=JasperFillManager.fillReport(jasper, params,conn);

就是将參数名和值put进入一map,然后再填充报表时将map传过去即可了.
2.矢量图,位图
Jasperreports支持矢量图与位图功能,是由于他封装了jfreechart(jfreechart是一个开源的图形解决方式库),使用ireport绘制矢量图或插入位图,能够不用我们写一行代码,这些jasperreports已经为我们所有封装好了,ireport仅仅提供了三种矢量图,各自是矩形,圆形,线条,以下先介绍怎样绘制矢量图,再介绍怎样插入位图.
 
初始工作:先新建一个空报表
绘制矩形:点击工具栏的 Rectangle button,在Detail区域,绘制一个矩形,绘制方法与windows自带的绘图工具一样,绘制好后,在该矩形上点右键,选属性,就可以设置该矩形的属性,大家能够依据自己须要进行设置,如设置前景色,背景色...
绘制圆形与绘制线条方法一样,仅仅须要在工具栏点对应的圆形工具或线条工具即可了.
非常easy吧.
 
问题出现
1.       图与图之间(更详细的说法,应该是元素与元素之间)不能有不论什么重叠,如重叠则仅仅能显示最上层的图.
2.       使用线条工具能够绘制斜线,当导出为pdf文件,没有不论什么问题,当导出html,xls文件时,发现斜线变成了矩形,解决方式是:使用外部图形编辑软件,绘制一条斜线,并保存为图片文件,再将这个图片文件插入到报表对应位置中.
在ireport中怎样測试预览pdf,html,xls…文件?
1.首先要设置一下pdf文件有什么预览。html文件用什么预览…
点Options -> Settings -> External Programs,在弹出的窗体中填写正确的外部程序。
如我的设置例如以下:
External Editor: C:/Program Files/EditPlus 2/editplus.exe (jrxml文件编辑器)
PDF Viewer: D:/Program Files/Adobe/Acrobat 7.0/Reader/AcroRd32.exe
HTML Viewer: C:/Program Files/Internet Explorer/IEXPLORE.EXE
XLS Viewer: "D:/Program Files/Microsoft Office/OFFICE11/EXCEL.EXE"
RTF Viewer: C:/Program Files/Windows NT/Accessories/wordpad.exe
该步操作仅仅要设置一次。以后就不须要再设置了。

2.设置你要预览的是什么文件。ireport默认预览的是pdf文件。但不是使用我们配制的外部程序预览的。而是使用jasperreports的JRViewer预览的。

你也能够设置使用我们配制的外部程序来预览,点Build -> PDF Preview,再点Execute (empty data source)button,就可以预览PDF文件。点Build -> HTML Preview,再点Execute (empty data source)button。就可以预览HTML文件。

注意:不论什么一个报表都必需要有一个数据源来为报表提供数据。
Execute (empty data source)的意思就是构造一个仅仅有一条记录的数据源传给报表,而且这条记录的值都是null,这个button在測试报表不须要数据时,很实用。
Execute (whit active connection)的意思就是将当前激活的连接或数据源传给报表,并生成报表。
 
位图
插入位图也非常easy,在工具栏上点击 Image button,然后在 Detail 区域绘制一个”矩形”(与绘制矩形操作同样),此时能够在你绘制的区域看到一个图片,在这个图片上点右键,选属性,选 Image 选项卡,点 “Find …”button,选择你要插入的图片,OK后,就能够看到你要插入的图片了.
 
在真实项目中怎样插入图片,动态改变图片?
在真实项目中可不能使用上面介绍的方法来插入图片,上面的方法仅仅是启到 hello world 的作用,要想在真实项目中插入图片,能够依照下面方法来配制.
1.       定义一个參数名为 imageName 类型:String 没有默认值 
2.       在报表设计界面中绘制一个Image,打开该Image的属性框,选Image选项卡,在Image Expression文本框中输入:$P{imageName},代表该图片的路径是由imageName的參数值来决定的,我们能够在程序中传入该參数的值.
怎样在程序中传入该參数值呢?
演示样例代码例如以下:
ServletContext context=request.getSession().getServletContext();
Map params
=new HashMap();
Params.put(“imageName”,context.getRealPath(“
/reports/test.jpg”));
JasperPrint print
=JasperFillManager.fillReport(jasper, params,conn);
 
传入不同的路径值就可以动态改变图片
 
在html中怎样显示图片?
当导出带有图片的报表到pdf,xls文件时,没有不论什么问题,但导出到html文件时,发现图片不能正常显示,不要急,jasperreports已经为我们提供了解决方式.解决过程例如以下:
1.将下面代码加入到web.xml文件里
<servlet>
    
<servlet-name>JasperreportsImageServlet</servlet-name>
    
<servlet-class>net.sf.jasperreports.j2ee.servlets.ImageServlet</servlet-class>
</servlet>
 
<servlet-mapping>
    
<servlet-name>JasperreportsImageServlet</servlet-name>
    
<url-pattern>/servlets/image</url-pattern>
</servlet-mapping>
2.程序代码按下面方式编写
ServletContext context=request.getSession().getServletContext();
Map params
=new HashMap();
Params.put(“imageName”,context.getRealPath(“
/reports/test.jpg”));
Map imageMap
=new HashMap();
request.getSession().setAttribute(
"IMAGES_MAP", imageMap);
 
JasperPrint print
=JasperFillManager.fillReport(jasper,params,conn);
request.getSession().setAttribute(net.sf.jasperreports.j2ee.servlets.ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,print);
 
JRHtmlExporter exporter 
= new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, response.getWriter());
exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP,imageMap);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath()
+"/servlets/image?

image=");
exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);

 
3.超链接,
有时我们想在报表中为某个keyword加入超链接或锚,使鼠标点击该keyword时跳转页面.针对这一小功能,jasperreports 也提供了支持,在ireport中操作非常easy.不是全部的元素都支持超链接,眼下我所知道支持超链接的经常使用元素有,动态文本框元素(Text Field),位图元素(Image),图表元素(Chart tool).这三种元素设置超链接的方法都是一样,所以仅仅介绍动态文本框怎样设置超链接.
 
怎样在ireport中插入超链接?
因为静态文本框不支持超链接,所以仅仅能通过动态文本框为静态文字设置超链接,操作方法例如以下所述:
1.在工具栏中选中 Text Field button,回到 Detail 区域,绘制一个Text Field (与绘制矩形方法一样),然后在该Text Field 上点右键,选 Edit Expresion,在弹出的窗体中输入表达式 "CSDN",然后再点 apply button.(注意: "CSDN"要包括双引號)
2.打开该 Text Field 的属性框,选 Hyperlink 选项卡,将 Hyperlink target 改为 blank,Hyperlink Type 改为 Reference,在Hyperlink Reference Expression框中输入"http://www.csdn.net",再点关闭.(注意: "http://www.csdn.net" 要包括双引號)
此时一个超链接已设置好,导出pdf,html文件看看,点击CSDN就可以弹出CSDN的网页.
 
怎样在ireport中插入锚?
事实上锚是超链接的一种特殊形式,因此支持超链接的元素都支持锚,不支持超链接的元素都不支持锚,锚的设置也非常easy,仅仅要你知道使用html的<a>设置锚,那么ireport也是差点儿相同的.
设置锚,也须要两步操作
1.设置锚对象
在 Title 区域绘制一个动态文本框,输入表达式 “2007年终財务报表”,再打开它的Hyperlink 选项卡,在 Anchor Name Expression 框中输入 “title”,点关闭.此时已定义了一个锚对象.它的锚名字是 title.
2.链接锚对象
在 Detail区域绘制一个动态文本框,输入表达式 “返回顶部”,再打开它的 Hyperlink 选项卡,将Hyperlink target改为 self,Hyperlink Type 改为 LocalAnchor,在Hyperlink Anchor Expression框中输入 “title”,点关闭.
一个锚链接已设置完成,导出pdf,html看看,当然,假设你的报表内容不多,那么锚起不到不论什么作用.
 
4.数据源,自己定义数据源
数据源顾名思义数据来源,即报表数据从何而来。jasperreports能够从数据库、XML文件、CSV文件、java.util.Collection对象以及自己定义数据源得到数据。在真实项目中,报表数据一般从数据库得到,以下介绍在ireport中怎样配制连接制数据库的数据源。操作过程例如以下:
 
说明:本例以MySql数据库来配制数据源
新建一个Document(报表文档),点 Data ->  Connections/Data Sources -> New -> Database JDBC Connection -> Next。在弹出的窗体中依照提示填写属性。例:
Name:mysql,
JDBC Driver:com.mysql.jdbc.Driver
JDBC URL:jdbc:mysql://localhost:3306/db_name
User Name:root
Password:your_password
 
填好后。单击Testbutton,如弹出 Connection test successful!。则代表数据源配制正确,并再点Save button。保存配制。

否则配制错误,请检查哪里出错。

配制好后,就可以连接数据库。
那么怎样用数据源查询数据库,并将查询结果显示在报表上呢?
说明:本例操作必须配制好数据库数据源才干正常操作。并且连接的数据库里要有表。

点 Data -> Report Query,在弹出的窗体中输入SQL查询语句:select * from t_users 。
假设sql语句正确将在窗体底部显示该表的全部字段。点击OK,即完毕了报表查询工作。

大家能够查看一下Fields面板,ireport已经自己主动将查询出的全部字段,定义成字段对象了(也就是最前面所说的定义字段)。
说完了怎样将数据查询出来,接下来的工作就是怎样将数据显示在报表界面上。

点View -> Fields打开Fields面板。在面板上随意选一个字段。将它拖到Detail区域的左上角对齐,再选一个字段拖到Detail区域的中上角。好了就用两字段做试验吧。仅仅要Detail区域够宽。大家能够多拖两个字段到Detail区域,拖到Detail区域的字段将在报表中显示。

调整好Detail区域的高度,执行(Build -> Execute (whit active connection))一下看看吧,假设你看到有正确数据,那恭喜你,你试验成功了!

 
自己定义数据源
有时,你可能须要自己定义一个数据源来满足你的需求,jasperreports对此也提供了良好支持。
仅仅要你实现JRDataSource接口,即可了,非常easy吧!
JRDataSource接口声明例如以下:
public interface JRDataSource
...{
public boolean next() throws JRException;
public Object getFieldValue(JRField jrField) throws
JRException;
}

下面我是我自己定义的一个数据源码:
1.先创建一个Bean类,该bean类属性全是大写,这是由于ireport自己主动定义字段时,字段名全是大写,你也能够手动改为小写,那么该bean类属性就能够为小写,你要确保bean类的属性名与字段名一致(包含大写和小写)。
 
package test;
import java.sql.Timestamp;
 
publicclass Bean 
...{
    privateintID;
    
private String NAME;
    
private String NICKNAME;
    privateintSCORE;
    privatefloatBALANCE;
    
private Timestamp LASTLOGINDATE;
 
    publicfloat getBALANCE() 
...{
       returnBALANCE;
    }

    publicvoid setBALANCE(
float balance) ...{
       
this.BALANCE = balance;
    }

    publicint getID() 
...{
       returnID;
    }

    publicvoid setID(
int id) ...{
       
this.ID = id;
    }

    
public Timestamp getLASTLOGINDATE() ...{
       returnLASTLOGINDATE;
    }

    publicvoid setLASTLOGINDATE(Timestamp lastLoginDate) 
...{
       
this.LASTLOGINDATE = lastLoginDate;
    }

    
public String getNAME() ...{
       returnNAME;
    }

    publicvoid setNAME(String name) 
...{
       
this.NAME = name;
    }

    
public String getNICKNAME() ...{
       returnNICKNAME;
    }

    publicvoid setNICKNAME(String nickname) 
...{
       
this.NICKNAME = nickname;
    }

    publicint getSCORE() 
...{
       returnSCORE;
    }

    publicvoid setSCORE(
int score) ...{
       
this.SCORE = score;
    }

}

2.创建实现数据源类
package test;
 
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
 
import org.apache.commons.beanutils.PropertyUtils;
 
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
 
publicclass TestBeanDataSource 
implements JRDataSource ...{
    
    
private List list;
    privateintindex
=-1;
 
    
public TestBeanDataSource() ...{
       list
=new ArrayList();
       Bean bean
=null;
       
       
for(int i=0;i<100;i++...{
           bean
=new Bean();
           bean.setID(i);
           bean.setNAME(
"name"+i);
           bean.setNICKNAME(
"nickname"+i);
           bean.setBALANCE((
float)(Math.random()*100*i));
           bean.setSCORE(i
*2);
           bean.setLASTLOGINDATE(
new Timestamp(System.currentTimeMillis()));
           list.add(bean);
       }

    }

    publicboolean next() 
throws JRException ...{
       
return ++index<list.size();
//     return false;
    }

 
    
public Object getFieldValue(JRField field) throws JRException ...{
       Bean bean
=(Bean)list.get(index);
       String fieldName
=field.getName();
       
       
try ...{
           
return PropertyUtils.getProperty(bean,fieldName);
       }
 catch (Exception e) ...{
           thrownew JRException(e);
       }

    }

    
public List getList() ...{
       returnlist;
    }

    publicvoid setList(List list) 
...{
       
this.list = list;
    }

 
}

3.在填充报表时将该DataSource传进去即可了。
JasperPrint print=JasperFillManager.fillReport(jasper,map,new TestBeanDataSource());
JRHtmlExporter exporter 
= new JRHtmlExporter();

exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);

exporter.exportReport();
此时报表数据的来源。就是从自己定义数据源中得到的100条记录。
 
怎样配制ireport支持自己定义的数据源?

1.把以上两个类创建好后,还要创建一个工厂类,用于生产自己定义数据源,该工厂类代码例如以下:
package test;
 
import net.sf.jasperreports.engine.JRDataSource;
 
publicclass TestCustomJRDataSourceFactory 
...{
    publicstatic JRDataSource test() 
...{
       returnnew TestBeanDataSource();
    }

}

2.因为是自己定义数据源,因此要将数据源引用的相关类,所有引入ireport的classpath。以供ireport调用,否则ireport会抛java.lang.ClassNotFoundException。比如我以上三个类都是放在d:/workspace/jasperreports/classes文件夹下,那么点 Options -> Classpath -> Add Folder 选择d:/workspace/jasperreports/classes,选择好后,点Save Classpath。
3.在ireport中创建一个自己定义数据源
点Data -> Connections/Data Sources -> New -> Custom JRDataSource
将弹出一窗体。依据提示填写内容,例:
Name:testCustom
Factory Class:test.TestCustomJRDataSourceFactory
The static method to call…:test
点击Test。弹出Connection test successful!。则代表自己定义数据源配制成功,否则请检查错误。

完毕了这三步,就能够在ireport中使用该自己定义数据源了。
 
怎样激活数据源?
创建好数据源后。ireport会自己主动激活它,因为同一时刻仅仅能有一个数据源处于激活状态,所以当你想激活其他数据源时可例如以下操作:
点Data -> Set Active Connection,在弹出的窗体中选择你要激活的数据源,再点OK就激活了。
仅仅有激活的数据源才会传给报表。

5.国际化(I18N)
国际化,又称I18N,由于国际化的英文是Internationalization,它以I开头,以N结尾,中间共18个字母。

Jasprereports通过ResourceBundle类支持I18N。
在ireport中怎样配制支持I18N?
我们新建一个报表。报表名为I18NTest。然后点Edit -> Internationalization -> Locale Files -> Create New Locale。输入_zh_CN,按OK,此时创建了一个支持中文的.properties文件。它的文件名称全写是I18NTest_zh_CN.properties,存放在与报表文件在同一文件夹下,我们再建一个支持英文的.properties文件,单击Create New Locale,输入_en。按OK。

假设你对ResourceBundle类有些了解,那么你就会知道输入的是什么意思。

创建属性文件后,下一步就是编辑它们,在Locale resource bundle窗体中,双击I18NTest_zh_CN.properties,此时就可以对编辑属性文件,我们在属性文件里添加一条i18n=嗨!

国际化,然后保存。

再编辑I18NTest_en.properties,在属性文件里添加一条i18n=hello I18n,保存。

以上操作即配制好了ireport支持i18n。
怎样调用显示属性文件内容?
在报表的不论什么一个区域都能够调用属性文件显示内容。
调用语法:$R{key} 或 str(key)
例:如要调用上面所配制的属性,使用 $R{i18n} 或 str(“i18n”)
格式化消息使用msg(pattern, arg1)
例:msg(”my name is {0}.”,”zhannggle”) 则输出:my name is zhanngle.
msg()有三个重载方式。msg(pattern,arg1), msg(pattern,arg1,arg1), msg(pattern,arg1,arg1,arg1)
差别就是參数不同而已,底层是通过MessageFormat.format(pattern,arguments)实现的。

使用属性文件格式化消息。

例有一属性文件定义例如以下:
a=jasperreports
b=ireport
hi=hello {0},hello {1}!
 
我们能够使用下面表达式显示消息
msg(str(“hi”),str(“a”),str(“b”))     输出:hello jasperreports,hello ireport!
在web开发中怎样存放属性文件?
将属性文件存放到WEB-INF/classes文件夹下,jasprereports会去这个文件夹搜索它。
提示:仅仅要配制好ireport支持I18N,就能够到报表文件存放文件夹找到自己主动生成好的属性文件。将它们拷到WEB-INF/classes文件夹下就能够了。

[讨论]:jasperreports是通过ResourceBundle.getBundle()获取属性文件,而getBundle()有三种重载方式getBundle(baseName),getBundle(baseName,locale),getBundle(baseName,locale,loader)
不知jasperreports是採用哪种方式,假设採用第一种,则依据server系统默认语言获取属性文件。而无论client请求哪种语言,如採用第二、三种。则会依据client请求语言去获取属性文件。而我在做測试时。无论将client设置成何种语言,都返回server系统默认语言。挻郁闷的,不知是我哪里错了,还是jasperreports採用了第一种方式去获取属性文件。没測出来,挻遗憾的,要查看源代码才知道。
 
6.脚本
脚本是一个java类。它用来运行指定的细节在打印期间。

脚本中的一些方法被报表引擎的调用,当一些特殊的事件,像创建一个新页或者处理detail 行。

实现一个脚本得继承net.sf.jasperreports.engine.JRAbstractScriptlet类。

net.sf.jasperreports.engine.JRAbstractScriptlet的声明例如以下:
package net.sf.jasperreports.engine;
/** *//**
@author Teodor Danciu (teodord@users.sourceforge.net)
@version $Id: JRDefaultScriptlet.java,v 1.3 2004/06/01 20:28:22
teodord Exp $
*/

public class JRDefaultScriptlet extends JRAbstractScriptlet
...{
public JRDefaultScriptlet() ...{ }
public void beforeReportInit() throws JRScriptletException
...{
}

public void afterReportInit() throws JRScriptletException
...{
}

public void beforePageInit() throws JRScriptletException
...{
}

public void afterPageInit() throws JRScriptletException
...{
}

public void beforeColumnInit() throws JRScriptletException
...{
}

public void afterColumnInit() throws JRScriptletException
...{
}

public void beforeGroupInit(String groupName) throws
JRScriptletException
...{
}

public void afterGroupInit(String groupName) throws
JRScriptletException
...{
}

public void beforeDetailEval() throws JRScriptletException
...{
}

public void afterDetailEval() throws JRScriptletException
...{
}

}

 
在ireport中怎样配制脚本?

Ireport默认不使用脚本,我们能够例如以下操作,使它使用脚本。

首先新建一个报表文档,报表名TestScriptlet
然后点Edit -> Report Properties -> Scriptlet Class -> Use ireport internal scriptlet support
此时ireport已经使用了一个内部定义好的脚本,该脚本是个空壳子。没有实现不论什么功能。

我们也能够编辑该脚本类。例如以下操作:
点Edit -> Scriptlet Editor,此时会弹出一个编辑脚本类的窗体,找到该脚本构造方法,在构造方法中加入一条语句:System.out.println(“create scriptlet…”);
在构造方法以下加入一个max方法,整个代码例如以下所看到的:
import net.sf.jasperreports.engine.*;
 
public class <ScriptletClassName> extends it.businesslogic.ireport.IReportScriptlet ...{
    
/** *//** Creates a new instance of JRIreportDefaultScriptlet */
public <ScriptletClassName>() ...{
       System.out.println(
"create scriptlet...");
}

public int max(int a,int b) ...{
       
if(a>=b) return a;
       
return b;
}

}

然后点Save保存。即创建了一个脚本。并再保存报表文件,此时你能够到报表文件文件夹找到一个TestScriptleScriptlet的java文件。这就是ireport自己主动生成的脚本类文件(脚本类名= 报表名+Scriptlet)。
在ireport中怎样调用脚本?
在报表创建时jasperreports会自己主动创建脚本对象,并在生成脚本时,jasperreports会自己主动调用对应的脚本方法,自己定义的方法须要我们手动调用才会运行。
例调用上面的max方法,可使用表达式:
((TestScriptletScriptlet)$P{REPORT_SCRIPTLET}).max ( 23,64)
$P{REPORT_SCRIPTLET}返回当前报表的脚本类
大家能够依据以上表达式举一反三调用脚本。
在web项目中怎样配制脚本?
当在web项目中使用脚本时。就不能依照上面的方式配制了,那样会找不到脚本类的。解决的方法例如以下4步:
1.在ireport的lib文件夹下找到ireport.jar,将它引入到项目中。
2.将ireport自己主动生成的java文件拷贝到项目src文件夹下(打包也行)。

3.编译项目后,将该项目的classes文件夹加入到ireport的classpath中。

4.点Edit -> Report Properties -> Scriptlet Class -> Use this scriptlet class…,在以下的文本框输入脚本类名。如打了包,要输入包名。点OK。编译ireport。
 
7.子报表
未完待续...

8.图表(饼图,柱图,线图)
未完待续...

9.导出pdf,xls,html...
下面是我导出各种报表Servlet源码。供大家參考!

package servlet;
 
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import oracle.jdbc.driver.OracleDriver;
import test.TestBeanDataSource;
 
import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.base.JRBaseReport;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.JRXmlExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;
 
 
publicclass ExportReportServlet 
extends HttpServlet ...{
 
    
/** *//**
     *Destructionoftheservlet.<br>
     
*/

    publicvoid destroy() 
...{
       
super.destroy(); // Just puts "destroy" string in log
       
// Put your code here
    }

 
    publicvoid doGet(HttpServletRequest request, HttpServletResponse response)
           
throws ServletException, IOException ...{
       
       String view
=request.getParameter("view");
       
if(view==null || view.trim().length()==0return;
       
       
if(view.equalsIgnoreCase("html")) doHtml(request,response);
       
if(view.equalsIgnoreCase("pdf")) doPdf(request,response);
       
if(view.equalsIgnoreCase("xls")) doExcel(request,response);
       
if(view.equalsIgnoreCase("xml")) doXml(request,response);
    }

    privatevoid doHtml(HttpServletRequest request, HttpServletResponse response)
    
throws ServletException, IOException ...{
       ServletContext context
=getServletContext();
       
//String jrxml=context.getRealPath("/WEB-INF/reports/Test1.jrxml");
       /**//*
       try {
           String jasper=context.getRealPath("/WEB-INF/reports/Test1.jasper");
           String html="/reports/"+System.currentTimeMillis()+".html";
           JasperRunManager.runReportToHtmlFile(jasper,context.getRealPath(html),new HashMap(),getConn());
           
           response.sendRedirect(request.getContextPath()+html);
           
       } catch (JRException e) { e.printStackTrace(); }
       
*/

       String reportDir
=context.getRealPath("/WEB-INF/reports");
       String jasper
=reportDir+"/Test1.jasper";
       
       response.setContentType(
"text/html");
       response.setCharacterEncoding(
"utf-8");
       Map map
=new HashMap();
       Map imageMap
=new HashMap();
       map.put(
"exportType","html");
       map.put(
"imageTest",context.getRealPath("/reports/star.gif"));
       map.put(
"SUBREPORT_DIR",reportDir+"/");
       request.getSession().setAttribute(
"IMAGES_MAP", imageMap);
       Connection conn
=getConn();
       
try ...{
           
//         JasperPrint print=JasperFillManager.fillReport(jasper,map,new TestBeanDataSource());
           JasperPrint print=JasperFillManager.fillReport(jasper,map,conn);
//         JasperPrint print=JasperFillManager.fillReport(jasper,map,new JREmptyDataSource());
           JRHtmlExporter exporter = new JRHtmlExporter();
 
            request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,print);
            
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
            exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, response.getWriter());
            exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP,imageMap);
            exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath()
+"/servlets/image?image=");
            exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
            exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
            
            exporter.exportReport();
 
       }
 catch (JRException e) ...
           StringWriter sw
=new StringWriter();
           PrintWriter pw
=new PrintWriter(sw);
           e.printStackTrace(pw);
           
           response.setContentType(
"text/plain");
           response.getOutputStream().print(sw.toString());
       }
 finally ...{
           
if(conn!=null)
              
try ...{
                  
if(!conn.isClosed()) conn.close();
              }
 catch (SQLException e) ...{
                  e.printStackTrace();
              }

       }

    }

    privatevoid doPdf(HttpServletRequest request, HttpServletResponse response)
    
throws ServletException, IOException ...{
       ServletContext context
=getServletContext();
       
//String jrxml=context.getRealPath("/WEB-INF/reports/Test1.jrxml");
       String reportDir=context.getRealPath("/WEB-INF/reports");
       String jasper
=reportDir+"/Test1.jasper";
       
       response.setContentType(
"application/pdf");
       Map map
=new HashMap();
       map.put(
"exportType","pdf");
       map.put(
"imageTest",context.getRealPath("/reports/star.gif"));
       map.put(
"SUBREPORT_DIR",reportDir+"/");
       Connection conn
=getConn();
       
try ...{
           OutputStream os
=response.getOutputStream();
           InputStream is
=new FileInputStream(jasper);
           JasperRunManager.runReportToPdfStream(is,os,map,conn);
//         JasperRunManager.runReportToPdfStream(is,os,map,new TestBeanDataSource());
           
           os.flush();
           os.close();
       }
 catch (JRException e) ...
           StringWriter sw
=new StringWriter();
           PrintWriter pw
=new PrintWriter(sw);
           e.printStackTrace(pw);
           
           response.setContentType(
"text/plain");
           response.getOutputStream().print(sw.toString());
       }
 finally ...{
           
if(conn!=null)
              
try ...{
                  
if(!conn.isClosed()) conn.close();
              }
 catch (SQLException e) ...{
                  e.printStackTrace();
              }

       }

    }

    privatevoid doExcel(HttpServletRequest request, HttpServletResponse response)
    
throws ServletException, IOException ...{
       ServletContext context
=getServletContext();
       String reportDir
=context.getRealPath("/WEB-INF/reports");
       String jasper
=reportDir+"/Test1.jasper";
       
       response.setContentType(
"application/vnd.ms-excel");
       response.setHeader(
"Content-Disposition","attachment;filename=Test1.xls");
       Map map
=new HashMap();
       map.put(
"exportType","xls");//设置參数,导出类型为xls 
       map.put("imageTest",context.getRealPath("/reports/star.gif"));// 设置參数,图片路径
       map.put("SUBREPORT_DIR",reportDir+"/");
       Connection conn
=getConn();
       
try ...{
            JasperReport report
=(JasperReport)JRLoader.loadObject(jasper);
            
try ...{//设置上边距,左边距,右边距,下边距为0
               java.lang.reflect.Field margin = JRBaseReport.class.getDeclaredField("leftMargin");
                margin.setAccessible(
true);
                margin.setInt(report, 
0);
                margin 
= JRBaseReport.class.getDeclaredField("topMargin");
                margin.setAccessible(
true);
                margin.setInt(report, 
0);
                margin 
= JRBaseReport.class.getDeclaredField("rightMargin");
                margin.setAccessible(
true);
                margin.setInt(report, 
0); 
                margin 
= JRBaseReport.class.getDeclaredField("bottomMargin");
                margin.setAccessible(
true);
                margin.setInt(report, 
0); 
                
//去掉Excel中隐藏的行,技巧
                java.lang.reflect.Field pageHeight = JRBaseReport.class.getDeclaredField("pageHeight");
                pageHeight.setAccessible(
true);
                pageHeight.setInt(report, Integer.MAX_VALUE);
                
             
//Don't print group header on each page
                if (null != report.getGroups())
                
...{
                    
for (int i = 0; i < report.getGroups().length; i++)
                    
...{
                       report.getGroups()[i].setReprintHeaderOnEachPage(
false);
                    }

                }

 
            }
 catch(Exception e) ...{ e.printStackTrace(); }
            
           JasperPrint print
=JasperFillManager.fillReport(report,map,conn);//填充数据
//         JasperPrint print=JasperFillManager.fillReport(report,map,new TestBeanDataSource());//填充数据
           
           JRAbstractExporter exporter
=new JExcelApiExporter();
           exporter.setParameter(JRExporterParameter.JASPER_PRINT,print);
           exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,response.getOutputStream());
           exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
                    Boolean.TRUE);
//删除空白行
           exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,Boolean.FALSE);//是否是每一页产生一个工作表
           exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);//是否为空白背景
 
           exporter.exportReport();
 
           response.getOutputStream().flush();
           response.getOutputStream().close();
       }
 catch (JRException e) ...{
           StringWriter sw
=new StringWriter();
           PrintWriter pw
=new PrintWriter(sw);
           e.printStackTrace(pw);
           
           response.setContentType(
"text/plain");
           response.getOutputStream().print(sw.toString());
       }
 finally ...{
           
if(conn!=null)
              
try ...{
                  
if(!conn.isClosed()) conn.close();
              }
 catch (SQLException e) ...{
                  e.printStackTrace();
              }

       }

    }

    privatevoid doXml(HttpServletRequest request, HttpServletResponse response)
    
throws ServletException, IOException ...{
       ServletContext context
=getServletContext();
       
//String jrxml=context.getRealPath("/WEB-INF/reports/Test1.jrxml");
       String reportDir=context.getRealPath("/WEB-INF/reports");
       String jasper
=reportDir+"/Test1.jasper";
       
       response.setContentType(
"text/xml");
       Map map
=new HashMap();
       map.put(
"exportType","xml");
       map.put(
"imageTest",context.getRealPath("/reports/star.gif"));
       map.put(
"SUBREPORT_DIR",reportDir+"/");
       Connection conn
=getConn();
       
try ...{
           JasperPrint print
=JasperFillManager.fillReport(jasper,map,conn);
           OutputStream os
=response.getOutputStream();
           JasperExportManager.exportReportToXmlStream(print,os);
           os.flush();
           os.close();
       }
 catch (JRException e) ...
           StringWriter sw
=new StringWriter();
           PrintWriter pw
=new PrintWriter(sw);
           e.printStackTrace(pw);
           
           response.setContentType(
"text/plain");
           response.getOutputStream().print(sw.toString());
       }
 finally ...{
           
if(conn!=null)
              
try ...{
                  
if(!conn.isClosed()) conn.close();
              }
 catch (SQLException e) ...{
                  e.printStackTrace();
              }

       }

    }

    privatestatic Connection getConn() 
...{
       
try ...{
           Class.forName(OracleDriver.
class.getName());
           
return DriverManager.getConnection("jdbc:oracle:thin:@202.192.xxx.xxx:1521:orc92","name","password");
       }
 catch (Exception e) ...{
           e.printStackTrace();
       }

       returnnull;
    }

    
    
/** *//**
     *Initializationoftheservlet.<br>
     *
     *@throwsServletExceptionifanerroroccure
     
*/

    publicvoid init() 
throws ServletException ...{
       
// Put your code here
    }

 
}

 
參考资料
1.  用户指南Ireport
2.  Jasperreports api
原文地址:https://www.cnblogs.com/yutingliuyl/p/7096304.html