论坛首页 Java企业应用论坛

使用报表开发工具Ireport生成Pdf报表的总结

浏览 6056 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-03-11   最后修改:2011-03-11

一、个人总结

要使用Ireport,首先都要配置生成模版,小弟到目前为止只用过两种方式,一种是使用JDBC数据源方式,就是在Ireport里写SQL语句,将需要的字段在SQL语句里输出出来,然后再拖拉构造模版文件。当报表比较复杂时,这种情况就需要写一些非常复杂的SQL语句,刚开始学习用Ireport时,以为只能这样生成模版,每天写一大堆SQL,很容易错不说,还弄得人头昏脑胀,痛不欲生啊,所幸,Ireport还有使用JavaBean作为数据源的方式。这两种方式使用起来个人感觉最主要的区别就是

JavaBean方式:

JRDataSource dataSource  = new JRBeanCollectionDataSource(mapList);
JasperReport  jasperReport = (JasperReport) JRLoader.loadObject(file);
jasperPrint = JasperFillManager.fillReport(jasperReport, null, dataSource);

 这种方式使用的是JasperFillManager.fillReport(jasperReport, parameters, dataSource),其中dataSource是通过传入的对象列表List<T>构造的

而JDBC方式:

Class.forName("com.mysql.jdbc.Driver");  
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost/test","root","root");  
JasperFillManager.fillReport(jasperReport, parameters, conn);

 

InputStream inputStream = getServletConfig().getServletContext().getResourceAsStream("report.jasper");           
JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters,connection);  
 

这这种方式使用的是JasperFillManager.fillReport(jasperReport, parameters, connection)、JasperFillManager.fillReport(inputStream, parameters, connection)最后一个参数是JDBC中的Connection

 

二、生成模版

JDBC方式比较简单,就不介绍了。下面只介绍JavaBean模式(小弟比较懒,下面只讲重点,废话就不多说了):

1、新建一个JavaBean类:

package com.techson.trms.testIeport;

public class CustomBean {
	
	private String city;  
	private Integer id;  
	private String name;  

	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}	
}

 2、配置Ireport的ClASSPATH为编译好的.class文件的路径 ,如图:


3、指定数据源:

在网上看到许多网友的这步的配置,发现有两种情况,一种是使用默认的数据源,一种是自己配置的数据源,刚开始时,还以为其中有一个错了,后来才发现,其实这根本没有关系的,只不过使用自己配置的数据源的,Preview时可以显示出预览数据,仅此而已。


 

默认数据源:


自己定义的数据源:

新建CustomFactory 数据源类:

public class CustomFactory {

	public static Collection<CustomBean> getBeans(){
		
		List<CustomBean> list = new ArrayList<CustomBean>();
		for(int i = 0 ;i<12;i++){
			CustomBean c = new CustomBean();
			c.setCity("city:"+i);
			c.setId(i+50);
			c.setName("name:"+i);
			list.add(c);
		}		
		return list;
	}
}

 

 

Factory class(the class that will produce the set): 为自己的CustomFactory的全路径。

下面输入的是类中定义的静态方法。

 

4、获取属性

在JavaBeanDataSource中输入自己新建的Bean类的全路径,点“Read Attributes” ,读取属性,选中需要的属性,加入到下面,然后点“OK”:


5、往模版中拖拉属性:


大致意思一下,咱主要说功能,美观方面就先不说了,呵呵。保存,模版文件example.jasper就生成了。可在Ireport中直接编译生成jasper文件,也可由程序自己生成。

 

三、项目中使用模版生成PDF文件

直接上代码:

点击“导出到PDF”

function doExport(){
				var time = new Date();
				window.open("<%=path%>/printEmail.do?doAction=pdf&time="+time,"window","menubar=no,status=no,resizable=no,scrollbars=1,width=800pt,height=600pt,top=100,left=300");
			}
 

进入这个Action(小弟用的是struts1,比较老,呵呵):

	@Override
	public String process(ActionForm form, HttpServletRequest request)
			throws Exception {

		HttpSession session = request.getSession();
		List<CustomBean> list = new ArrayList<CustomBean>();
		for(int i = 0 ;i<12;i++){
			CustomBean c = new CustomBean();
			c.setCity("city:"+i);
			c.setId(i+50);
			c.setName("name:"+i);
			list.add(c);
		}
		String fileName =createPDFByXmlName("example", list, session);
		session.setAttribute("PDFNAME", fileName);
		return "success";
	}
 
	public static String createPDFByXmlName(String reportName, List mapList,HttpSession session) throws UnsupportedEncodingException, JRException {
		String path = "WebRoot/reports";
		if (session != null) {
			path = session.getServletContext().getRealPath("reports");
		}
		JasperReport jasperReport;
		JasperPrint jasperPrint;		
		
		try {
			File file = new File(path + "/" + reportName + ".jasper");
			//如果jasper文件不存在,就调用jrxml文件编译生成
			//JasperCompileManager.compileReportToFile(String sourceFileName, String destFileName)
			if (!file.exists()) {
				JasperCompileManager.compileReportToFile(path + "/"+ reportName + ".jrxml",path + "/"+ reportName + ".jasper");
			}

			jasperReport = (JasperReport) JRLoader.loadObject(file);
			
			JRDataSource dataSource  = new JRBeanCollectionDataSource(mapList);
				//此处为关键,将对象列表设为数据源			
			jasperPrint = JasperFillManager.fillReport(jasperReport, null, dataSource);
				//因模版上没有传入参数,所以此处第二个参数为空

			String fileName = "pdf/"+reportName+session.getId()+".pdf";		
			File fi = new File(path+"/pdf");
			if(!fi.exists()){
				fi.mkdir();
			}			
			//生成方法1
			JRPdfExporter exporter = new JRPdfExporter();
			exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRPdfExporterParameter.CHARACTER_ENCODING,"UTF-8");
			exporter.setParameter(JRPdfExporterParameter.OUTPUT_FILE_NAME, path+"/"+fileName);
								//注意此处用的不是JRPdfExporterParameter.OUTPUT_FILE,要用这个,还需新建File
			exporter.exportReport();
			
			//生成方法2
			try {					
				JasperExportManager.exportReportToPdfFile(jasperPrint,path+"/"+fileName);
			} catch (Exception e) {
				e.printStackTrace();
			}		
			session.getServletContext().setAttribute("FilePath", path+"/pdf");
			return fileName;
		}catch(JRException e){
			e.printStackTrace();			
			throw new JRException(e);
		}
	}

 代码注释里写的很详细了。。。

其实到这就已经介绍完了,不过既然写了,就弄完吧,o(∩_∩)o 哈哈

 

成功后跳转:

<action path="/printEmail" type="com.techson.trms.struts.action.PrintEmailAction">
			<forward name="success" path="/printEmail.jsp" />
		</action>

 printEmail.jsp文件:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory
			.getLog("print.jsp");
	log.warn(" enter print.jsp");
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <script type="text/javascript">
  	function init(){
  		var time = new Date();
	  	var url='<%=basePath %>'+"reports/"+'${PDFNAME}'+"?doAction=pdf&time"+time;
  		window.location.href=url;
  	}
  </script>
  </head>
  <body onload="init();">

 


 最后实现的效果是点击导出PDF文件后,弹出一个浏览器框,提示下载。

最后效果:


 

This is  all !  o(∩_∩)o 哈哈

 

另:

实际调试中发现代码到编译jrxml文件为jasper文件时死活过不去,替换了groovy.jar架包为groovy-1.5.7.jar后,还不行,又替换为本文所使用的Ireport3.7.6中的groovy-all-1.7.5.jar,编译通过!Game Over !

  • 大小: 8.7 KB
  • 大小: 43.8 KB
  • 大小: 34.3 KB
  • 大小: 40.1 KB
  • 大小: 59.4 KB
  • 大小: 12.2 KB
  • 大小: 17.5 KB
  • 大小: 76.6 KB
   发表时间:2012-02-18  
怎么我是倒过来JDBC,真的用不了啊,只能一直试,都不知道出什么错,我用的是access

JavaBean 超简单的, 建dataset就可以了
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics