iRport: http://ireport.sourceforge.net
Jasperreport: http://jasperreports.sourceforge.net
安装就不用说了,但是要理解Ireport和JasperReport的关系十分重要,Ireport是设计报表的图形界面,在Ireport里新建一个报表是以.jrxml的形式保存的,而最终要用到的是将.jrxml的文件编译为.jsper的文件。.jasper文件就是JaserReport需要调用的报表模版,JasperReport的强大功能就在于它能将.jasper转化为各种文件的格式,如xls,rtf,pdf等等最常用的文件格式。
要将.jsper文件应用在项目中,首先要做几样准备工作:
1.将安装好的Ireport,找到它下面的lib目录,再把jasperreports-1.3.0.jar这个包复制出来(这个包是JasperReport导出的关键),然后将这个包导入到需要应用的项目中,然后在eclipse中重新构建整个项目,这是最关键的第一步。
2.如果导出出现乱码的问题,需要引入iText亚洲语言包, 可以在 http://www.lowagie.com/iText/ 查看关于iText的相关信息,包括源代码,文档.
3.设计好报表,将报表编译为.jsper文件,这些文件在iReport的安装路径下,很容易找到。
现在万事俱备,只欠东风了。我在开始写程序的的时候,在网上找了好些代码,而导出的过程中用到的类JRRtfExporter的源代码也踩过,并且发现了http://www.koders.com这个非常好的网站,这是开源项目的必备,在上面基本上很多类的源码也能查到。
接着自己封装了一个JasperReport类,而这个类可以实现导出各种格式的文件,代码如下:
package common.ireport;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.*;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import java.util.List;
import java.io.*;
import com.log.Logger;
/**
* IReport+JasperReport导出报表类接口
* <p>Title: 导出报表类</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2007</p>
* <font class=companyfont>
* CES
* </font>
* @author 野谷子
* @version 1.0.2007.02.14
*/
public class JasperReport {
private Logger logger = new Logger("common.ireport.JasperReport");
/** Creates a new instance of MyReport */
public JasperReport() {
}
/*
* 导出单个报表为rtf或word
* @param JasperPrint,OutputStream
* @ 页面设置response.setContentType("application/msword");
* @ 页面设置response.setHeader("Content-disposition","attachment;filename=fileName.doc");
* @ 页面设置response.setContentLength(bytes.length);
*/
public void exportReportToRTF(JasperPrint jasperPrint,OutputStream out){
JRRtfExporter rtfExporter = new JRRtfExporter();
rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
try {
rtfExporter.exportReport();
logger.debug("Genertate the RTF report ok! :" + out);
} catch (JRException e) {
e.printStackTrace();
logger.error("Generate the RTF report file ERROR!");
}
}
/*
* 导出多个报表为rtf或word
* @param List,OutputStream
* @ 页面设置response.setContentType("application/msword");
* @ 页面设置response.setHeader("Content-disposition","attachment;filename=fileName.doc");
* @ 页面设置response.setContentLength(bytes.length);
*/
public void exportReportListToRTF(List jasperPrints,OutputStream out){
JRRtfExporter rtfExporter = new JRRtfExporter();
rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT_LIST, jasperPrints);
rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
try {
rtfExporter.exportReport();
logger.debug("Genertate the mutiply RTF report ok! :" + out);
} catch (JRException e) {
e.printStackTrace();
logger.error("Generate the mutiply RTF report file ERROR!");
}
}
/*
* 导出单个报表为PDF
* @param JasperPrint,OutputStream
* @ 页面设置response.setContentType("application/pdf");
* @ 页面设置response.setHeader("Content-disposition","attachment;filename=fileName.pdf");
* @ 页面设置response.setContentLength(bytes.length);
*/
public void exportReportToPDF(JasperPrint jasperPrint,OutputStream out){
JRPdfExporter pdfExporter = new JRPdfExporter();
pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
pdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
try {
pdfExporter.exportReport();
logger.debug("Genertate the PDF report ok! :" + out);
} catch (JRException e) {
e.printStackTrace();
logger.error("Generate the PDF report file ERROR!");
}
}
/*
* 导出单个报表为XLS
* @param JasperPrint,OutputStream
* @ 页面设置response.setContentType("application/vnd.ms-excel");
* @ 页面设置response.setHeader("Content-disposition","attachment;filename=fileName.xls");
* @ 页面设置response.setContentLength(bytes.length);
*/
public void exportReportToXLS(JasperPrint jasperPrint,OutputStream out){
JRXlsExporter xlsExporter = new JRXlsExporter();
xlsExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
xlsExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
try {
xlsExporter.exportReport();
logger.debug("Genertate the XLS report ok! :" + out);
} catch (JRException e) {
e.printStackTrace();
logger.error("Generate the XLS report file ERROR!");
}
}
/*
* 导出单个报表为HTML
* @param JasperPrint,OutputStream
* @ 页面设置response.setContentType("text/html");
* @ 页面设置response.setHeader("Content-disposition","attachment;filename=fileName.html");
* @ 页面设置response.setContentLength(bytes.length);
*/
public void exportReportToHTML(JasperPrint jasperPrint,OutputStream out){
JRHtmlExporter htmlExporter = new JRHtmlExporter();
htmlExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
htmlExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
htmlExporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
htmlExporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.FALSE);
try {
htmlExporter.exportReport();
logger.debug("Genertate the HTML report ok! :" + out);
} catch (JRException e) {
e.printStackTrace();
logger.error("Generate the HTML report file ERROR!");
}
}
/*
* 导出单个报表为CSV
* @param JasperPrint,OutputStream
*/
public void exportReportToCSV(JasperPrint jasperPrint,OutputStream out){
JRCsvExporter csvExporter = new JRCsvExporter();
csvExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
csvExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
try {
csvExporter.exportReport();
logger.debug("Genertate the CSV report ok! :" + out);
} catch (JRException e) {
e.printStackTrace();
logger.error("Generate the CSV report file ERROR!");
}
}
/*
* 导出单个报表为TXT
* @param JasperPrint,OutputStream
* @ 页面设置response.setContentType("text/html");
* @ 页面设置response.setHeader("Content-disposition","attachment;filename=fileName.txt");
* @ 页面设置response.setContentLength(bytes.length);
*/
public void exportReportToTXT(JasperPrint jasperPrint,OutputStream out){
JRTextExporter txtExporter = new JRTextExporter();
txtExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
txtExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
txtExporter.setParameter(JRTextExporterParameter.CHARACTER_WIDTH, new Integer(80));
txtExporter.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT, new Integer(25));
try {
txtExporter.exportReport();
logger.debug("Genertate the TXT report ok! :" + out);
} catch (JRException e) {
e.printStackTrace();
logger.error("Generate the TXT report file ERROR!");
}
}
/*
* 导出单个报表为XML
* @param JasperPrint,OutputStream
*/
public void exportReportToXML(JasperPrint jasperPrint,OutputStream out){
try {
JasperExportManager.exportReportToXmlStream(jasperPrint, out);
logger.debug("Genertate the XML report ok! :" + out);
} catch (JRException e) {
e.printStackTrace();
logger.error("Generate the XML report file ERROR!");
}
}
}
然后写了一个Control类用于封装.jasper文件,并获取其对象,代码如下:
package common.ireport;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.*;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.util.*;
import net.sf.jasperreports.view.*;
import java.util.*;
import java.util.List;
import java.sql.*;
import java.io.*;
import java.net.URL;
/**
* 导出报表控制类
* <p>Title: 导出报表控制类</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2007</p>
* <font class=companyfont>
* CES
* </font>
* @author 野谷子
* @version 1.0.2007.02.14
*/
public class JsperReportControl {
private Logger logger = new Logger("common.ireport.JsperReportControl");
private Query query = new Query();
//定义报表模版路径
private String PREFIX = "/ireportFile/";
//定义后缀名
private String SUFFIX = ".jasper";
public JsperReportControl() {
}
/*
* 取得报表模版的对象
* 单个参数的情况
* @param 报表名称:strFileName
* @param 参数名称:strParamName
* @param 参数值:strParamValue
* @return JasperPrint
*/
public JasperPrint getJsperPrint(String strFileName,String strParamName,String strParamValue) throws SQLException{
JasperPrint jasperPrint = null;
String strJasper = this.getClassPath()+PREFIX + strFileName + SUFFIX;
Map params = new HashMap();
params.put(strParamName,strParamValue);
//定义数据源连接对象
Connection conn = null;
query.createConnection(CommonManage.CONN);
conn = query.getConnection();
try {
//用JasperFillManager类导入.jasper文件,参数和数据源
jasperPrint = JasperFillManager.fillReport(strJasper, params, conn);
try{
if(conn==null){
conn.close();
}
}catch(SQLException sqle){
logger.error("关闭数据库连接错误"+sqle);
}
}catch(Exception e){
logger.error("getJsperPrint(String strFileName,String strParamName,String strParamValue) Error"+e);
}
return jasperPrint;
}
/**
* 在类中取得当前文件所在的相对路径与绝对路径
*
* @return String
*/
public String getClassPath(){
String strClassName = getClass().getName();
String strPackageName = "";
String strURL = "";
if(getClass().getPackage() != null)
{
strPackageName = getClass().getPackage().getName();
}
//System.out.println("ClassName:" + strClassName);
//System.out.println("PackageName:" + strPackageName);
String strClassFileName = "";
if(!"".equals(strPackageName))
{
strClassFileName = strClassName.substring(strPackageName.length() + 1,strClassName.length());
}
else
{
strClassFileName = strClassName;
}
//System.out.println("ClassFileName:" + strClassFileName);
String strTempName = strClassFileName+".class";
try
{
URL url = null;
url = getClass().getResource(strClassFileName + ".class");
strURL = url.toString();
System.out.println(strURL);
logger.info("strURL="+strURL);
}
catch(Exception ex)
{
ex.printStackTrace();
}
//取.jasper文件的绝对路径
strURL= strURL.substring("file:".length(),strURL.length()-strTempName.length());
System.out.println("strURL="+strURL);
return strURL;
}
}
期间在取绝对路径时出现了问题,在本机测试可以通过,但放在服务器上报错,原因是本机是windows系统,而服务器是linux系统,到现在我觉得最大的原因是getClass().getResource()这个方法在linux系统上取不到资源的位置而报错。
最后就是所写的jsp页面了,代码如下:
<%@ page import="java.util.Vector" %>
<%@ page import="java.io.*" %>
<%@ page import="java.io.OutputStream" %>
<%@ page import="java.util.List" %>
<%@ page import="net.sf.jasperreports.engine.*" %>
<%@ page import="common.ireport.JsperReportControl"%>
<%@ page import="common.ireport.JasperReport"%>
<%
String strMode = WebUtil.getParam(request,"mode").equals("")?"":WebUtil.getParam(request,"mode");
JsperReportControl jsperReportControl = new JsperReportControl();
JasperReport jasperReport = new JasperReport();
strFileName1 = "quanlitySupervise_page1";
strFileName2 = "quanlitySupervise_page2";
strFileName3 = "quanlitySupervise_page3";
strFileName4 = "quanlitySupervise_page4";
strFileName5 = "quanlitySupervise_page5";
strFileName6 = "quanlitySupervise_page6";
strFileName7 = "quanlitySupervise_page7";
strFileName8 = "quanlitySupervise_page8";
String strParamName="ID";
String strParamValue=strProjectID;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String strQueryConditionTmp="projectName="+strProjectName;
QueryCtrl queryCtrl = new QueryCtrl();
String str="";
if(strMode.equals("out")){
JasperPrint jasperPrint1 = jsperReportControl.getJsperPrint(strFileName1,strParamName,strParamValue);
JasperPrint jasperPrint2 = jsperReportControl.getJsperPrint(strFileName2,strParamName,strParamValue);
JasperPrint jasperPrint3 = jsperReportControl.getJsperPrint(strFileName3,strParamName,strParamValue);
JasperPrint jasperPrint4 = jsperReportControl.getJsperPrint(strFileName4,strParamName,strParamValue);
JasperPrint jasperPrint5 = jsperReportControl.getJsperPrint(strFileName5,strParamName,strParamValue);
JasperPrint jasperPrint6 = jsperReportControl.getJsperPrint(strFileName6,strParamName,strParamValue);
JasperPrint jasperPrint7 = jsperReportControl.getJsperPrint(strFileName7,strParamName,strParamValue);
JasperPrint jasperPrint8 = jsperReportControl.getJsperPrint(strFileName8,strParamName,strParamValue);
List reportlist = (List)new java.util.ArrayList();
reportlist.add(jasperPrint1);
reportlist.add(jasperPrint2);
reportlist.add(jasperPrint3);
reportlist.add(jasperPrint4);
reportlist.add(jasperPrint5);
reportlist.add(jasperPrint6);
reportlist.add(jasperPrint7);
reportlist.add(jasperPrint8);
//导出单页测试用
//jasperReport.exportReportToRTF(jasperPrint1,baos);
//整合多页导出
jasperReport.exportReportListToRTF(reportlist,baos);
byte[] bytes;
bytes = baos.toByteArray();
response.setContentType("application/ms_word");
String strDocName = "attachment;filename="+strProjectID+".doc";
response.setHeader("Content-disposition",strDocName);
response.setContentLength(bytes.length);
ServletOutputStream ouputStream = response.getOutputStream();
ouputStream.write(bytes, 0, bytes.length);
ouputStream.flush();
ouputStream.close();
}
}
%>
结尾:在本机测试通过了,但放于服务器出现了错误:Can't connect to X11 window server using ':0.0' as the value of the DISPLAY
而在windows系统中却能正确运行,原因是程序调用了图形界面的功能,而windows很好的支持图形界面,linux却不能很好的支持,需要修改linux中的DISPLAY的变量:
下面有几种方法:
1. 对于tomcat服务器:找到脚本:catalina.sh,
在/usr/local/tomcat/bin/catalina.sh中修改为
JAVA_OPTS="-Djava.awt.headless=true"或者CATALINA_OPTS="-Djava.awt.headless=true"
echo "Using CATALINA_BASE: $CATALINA_BASE"
echo "Using CATALINA_HOME: $CATALINA_HOME"
echo "Using CATALINA_TMPDIR: $CATALINA_TMPDIR"
echo "Using RUNJAVA: $_RUNJAVA"
echo "Using JAVA_OPTS: $JAVA_OPTS"
2.对于服务器中oracle自带的JSP server,找到jserv.properties这个配置文件,在上面添加:
wrapper.env=DISPLAY=<SERVERNAME>:0
3.或者用root身份执行一下xhost +命令,
第一种情况:DISPLAY在远程数据库中没有正确定义,需要:
set DISPLAY=localComputer:0
export DISPLAY(取决于shell的不同而命令不同)
第二种情况:图形界面的功能不能在远程登陆的用户中定义和使用,需要:
使用oracle用户登录xwindow: 应用xhost +命令
终于写完了,因为刚开始的时候我在网上找资料发现有用的、系统的资料少之又少,而且JasperReport的文档又是收费的,现在写我的过程出来希望能给想应用JasperReport的仁兄参考下。