因为新近项目的需要,最近
我一直在研究报表工具。其中一个就是J
asperReports。J
asperReports是一个非常流行的用Java写成的开源(LGPL)报表工具库。但是很不幸,它缺乏好的文档所以
我费尽心机才运行起来一个简单的报表。经过一段时间的琢磨,
我做出了一个简单的报表,本文就是总结了入门J
asperReport需要做的一些工作。在资源信息里你可以找到关于J
asperReports的更多的文档和信息。
快速上手
J
asperReports的报表是用XML文件来定义的,约定用jrxml作后缀名。一个典型的jrxml文件包含以下元素:
- <!--[if !supportLists]--> <!--[endif]--><jsperReport> - 根元素
- <!--[if !supportLists]--><title> - 报表的标题,一篇报表里只在开头打印一次
- <!--[if !supportLists]--><pageHeader> - 页眉,报表每页开头打印一次
- <!--[if !supportLists]--><!--[endif]--><detail> - 报表正文
- <!--[if !supportLists]--><!--[endif]--><pageFooter> - 页脚,报表每页末尾打印一次
- <!--[if !supportLists]--><!--[endif]--><band> - 定义报表部件,以上所有元素都包含一个band元素作为他们唯一的子元素
除了root元素,所有的元素都是可选的。这里是一个jrxml文件的例子,它将生成一个显示字符串“Hello World!”的简单报表。
<?xml version="1.0"?>
<!DOCTYPE j
asperReport
PUBLIC "-//J
asperReports//DTD Report Design//EN"
"http://j
asperreports.sourceforge.net/dtds/j
asperreport.dtd">
<j
asperReport name="Simple_Report">
<detail>
<band height="20">
<staticText>
<reportElement x="180" y="0" width="200" height="20"/>
<text><![CDATA[Hello World!]]></text>
</staticText>
</band>
</detail>
</j
asperReport>
在这个简单的例子中,
我没有写可选项<title>, <pageHeader>还有<pageFooter>。<staticText>元素,顾名思义,在报表上显示静态的文本,就像你所看到的,它包含了一个单独的<text>元素定义将要显示的文本。
jrxml文件需要“编译”成J
asperReports规范的二进制格式,可以调用类net.sf.j
asperreports.engine.J
asperCompileManager的方法compileReport()来实现。这个方法有几种重载的形式,在
我们的例子中,
我们将用到的是单个字符串为参数的方法。参考J
asperReport文档以获得这个方法其他版本的详细信息。
public class J
asperReportsIntro
{
public static void main(String[] args)
{
try
{
jasperReport = JasperCompileManager.compileReport(
"reports/jasperreports_demo.jrxml");
jasperPrint = JasperFillManager.fillReport(
jasperReport, new HashMap(), new JREmptyDataSource());
JasperExportManager.exportReportToPdfFile(
jasperPrint, "reports/simple_report.pdf");
}
catch (JRException e)
{
e.printStackTrace();
}
}
}
一个jrxml文件只需要编译一次,但在这个简单例子中,每次执行程序都会被编译。在报表生成之前,需要用数据来“填充”它,在这里
我们调用net.sf.j
asperreports.engine.J
asperFillManager类里的fillReport()方法。同样的,它也有许多重载的形式,这里
我们用到了其中一个具有三个参数的方法,第一个是J
asperReport的实例, 第二个是HashMap,它可以包含任何要传递给report的参数,第三个参数对象要实现JRDataSource接口。这个方法的使用在
我们的例子里面是:
j
asperPrint = J
asperFillManager.fillReport(
j
asperReport, new HashMap(), new JREmptyDataSource());
因为
我们的例子里的report类不需要任何参数,所以传给一个它一个空的HashMap,第三个参数net.sf.j
asperreports.engine.JREmptyDataSource是一个实现了JRDataSource接口的简便类,这个基本类不包含任何数据。
The parameters are self-explanatory.
最后,在例子中,
我们将报表导出为PDF文件,可以用Adobe Acrobat, XPDF, Evince或其他PDF阅读工具打开。在例子中的代码是:J
asperExportManager.exportReportToPdfFile(
j
asperPrint, "reports/simple_report.pdf");
结束
J
asperReports是一个非常优秀且流行的开源报表引擎,这篇指导提供了快速上手J
asperReports的足够信息。要获得更丰富的文档,J
asperSoft发布了一部电子书:
The JasperReports Ultimate Guide