`
jinyanhui2008
  • 浏览: 312140 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
社区版块
存档分类
最新评论

使用jasperreports制作报表(导出pdf excel html)

阅读更多

最近项目需要制作报表类操作,所以在网上查了查资料找了找朋友帮我整了整,现在已经能跟顺利跑起来了,所以将这些东东写成文档,以备忘记。

首先需要下载 ireport ,这个是进行报表设计的,如果不会使用,可以上网查查具体用法,等会我会贴上我自己做的一个简单的小例子。

需要下载的资源:

ireport http://jasperforge.org/plugins/project/project_home.php?group_id=83

JasperReport  http://jasperforge.org/plugins/project/project_home.php?group_id=102

如果需要支持中文还需要以下两个包:

iTextAsian http://nchc.dl.sourceforge.net/sourceforge/itext/iTextAsian.jar

iText  http://nchc.dl.sourceforge.net/sourceforge/itext/iText-2.1.5.jar 

另外在发布工程的时候可能会提示缺少以下几个包:

commons-beanutils http://labs.xiaonei.com/apache-mirror/commons/beanutils/binaries/commons-beanutils-1.8.0-bin.zip

commons-digester http://apache.mirror.phpchina.com/commons/digester/binaries/commons-digester-2.0-bin.zip

commons-collections http://apache.freelamp.com/commons/collections/binaries/commons-collections-3.2.1-bin.zip

poi http://apache.mirror.phpchina.com/poi/release/bin/

commons-ogging http://commons.apache.org/downloads/download_logging.cgi

上述提到的包均需要拷贝到工程当中。

 

这样子基本上我们需要的包就算完整了,然后就是我们jsp页面了,我的所有导出数据都是通过这个jsp页面来实现的。

<!-- %@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%-->
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.util.Map"%>
<%@page import="java.io.File"%>
<%@page import="java.util.HashMap"%>
<%@page import="net.sf.jasperreports.engine.JasperCompileManager"%>
<%@page import="net.sf.jasperreports.engine.JasperRunManager"%>
<%@page import="net.sf.jasperreports.engine.JasperPrint"%>
<%@page import="net.sf.jasperreports.engine.JasperFillManager"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="com.wfy.system.dao.BasicToolsDAO"%>
<%@page import="java.util.Enumeration"%>
<%@page import="net.sf.jasperreports.engine.export.JRXlsExporter"%>
<%@page import="net.sf.jasperreports.engine.JRExporterParameter"%>
<%@page import="net.sf.jasperreports.engine.export.JRXlsExporterParameter"%>
<%@page import="java.io.ByteArrayOutputStream"%>
<%@page import="net.sf.jasperreports.engine.export.JRHtmlExporterParameter"%>
<%@page import="net.sf.jasperreports.engine.export.JRHtmlExporter"%>
<%
	WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
	BasicToolsDAO bo = (BasicToolsDAO) wac.getBean("BasicToolsDAO");//连接服务器,从数据看中获取数据库的connection。

	String rptpath = application.getRealPath("/reports/jasper");//我们将要使用的报表模板保存路径
	
	String reportname = request.getParameter("reportName");//获取报表名称
	Enumeration parameters = request.getParameterNames();//解析报表显示需要的参数
	JasperCompileManager.compileReportToFile(rptpath + "/" + reportname +".jrxml");//编译报表模板源码

	try {
		Connection con = bo.getDataSourceConnection();//创建数据源
		File rpt = new File(rptpath + "/" + reportname + ".jasper");//获取报表模板

		/*解析request传入的条件,传入条件格式为:(条件名_类型=参数)*/
		Map map = new HashMap();
		while(parameters.hasMoreElements()){
			String parameter = parameters.nextElement().toString();
			if(!parameter.equals("reportName") && !parameter.equals("reportType")){
				String[] p = parameter.split("_");
				if ("int".equals(p[1])) {
					map.put(p[0], Integer.parseInt(request.getParameter(parameter)));
				} else if ("string".equals(p[1])) {
					String str = request.getParameter(parameter);
					if(str==null){
						str = "";
					}
					map.put(p[0], str);
				} else if ("float".equals(p[1])) {
					map.put(p[0], Float.parseFloat(request.getParameter(parameter)));
				} else if ("double".equals(p[1])) {
					map.put(p[0], Double.parseDouble(request.getParameter(parameter)));
				} else if ("date".equals(p[1])) {
					map.put(p[0], (request.getParameter(parameter)==null || "".equals(request.getParameter(parameter).trim())) ? null : new SimpleDateFormat().parse(request.getParameter(parameter)));
				} else if ("long".equals(p[1])) {
					map.put(p[0], Long.parseLong(request.getParameter(parameter)));
				}
			}
		}
		
		//将解析完的参数传入报表模板中并生成报表
		if(request.getParameter("reportType").equals("pdf")){
			byte[] bytes = JasperRunManager.runReportToPdf(rpt.getPath(), map, con);
			response.setContentType("application/pdf");
			response.setContentLength(bytes.length);
			ServletOutputStream ouputStream = response.getOutputStream();
			ouputStream.write(bytes, 0, bytes.length);
			ouputStream.flush();
			ouputStream.close();
			con.close();
			out.clear();
			out = pageContext.pushBody();
		}else if(request.getParameter("reportType").equals("xls")){
			JRXlsExporter exporter = new JRXlsExporter();
			ByteArrayOutputStream oStream = new ByteArrayOutputStream();
			JasperPrint jasperPrint = JasperFillManager.fillReport(rpt.getPath(), map, con);
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, oStream);
			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();
			
			byte[] bytes = oStream.toByteArray();
			response.setContentType("application/vnd.ms-excel");
			response.setContentLength(bytes.length);
			ServletOutputStream ouputStream = response.getOutputStream();
			ouputStream.write(bytes, 0, bytes.length);
			ouputStream.flush();
			ouputStream.close();
			con.close();
			out.clear();
			out = pageContext.pushBody();
		}else{
			//生成html
			JRHtmlExporter exporter = new JRHtmlExporter();
			ByteArrayOutputStream oStream = new ByteArrayOutputStream();
			JasperPrint jasperPrint = JasperFillManager.fillReport(rpt.getPath(), map, con);
			exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
			exporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
			exporter.setParameter(JRHtmlExporterParameter.CHARACTER_ENCODING, "utf-8");
			exporter.setParameter(JRHtmlExporterParameter.OUTPUT_STREAM, oStream);
			exporter.exportReport();
			byte[] bytes = oStream.toByteArray();
			response.setContentType("text/html");
			response.setContentLength(bytes.length);
			response.setCharacterEncoding("utf-8");
			ServletOutputStream ouputStream = response.getOutputStream();
			ouputStream.write(bytes, 0, bytes.length);
			ouputStream.flush();
			ouputStream.close();
			con.close();
			out.clear();
			out = pageContext.pushBody();
		}
	} catch (Exception ex) {
		System.out.print("Jasper Output Error:" + ex.getMessage());
		ex.printStackTrace();
	}
	
%>

 

 

 这个是公共的报表生成模板,有了它一切报表都可能通过他生成了。

下一步就是报表的设计了,设计的时候我们要用ireport工具了,说实在他的功能还是很强大的,我自己做了一个简单的小例子,用的是我们的数据库,你们只需要简单修改成你们的数据库,就很容易实现了。

 

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="report" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
	<property name="ireport.scriptlethandling" value="0"/>
	<property name="ireport.encoding" value="UTF-8"/>
	<import value="net.sf.jasperreports.engine.*"/>
	<import value="java.util.*"/>
	<import value="net.sf.jasperreports.engine.data.*"/>
	<reportFont name="MyFont" isDefault="true" fontName="宋体" size="10" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
	<style name="MyStyle" isDefault="true" fontName="宋体" pdfFontName="STSong-Light" pdfEncoding="UniGB-UCS2-H" isPdfEmbedded="true"/>
	<queryString>
		<![CDATA[select * from test]]>
	</queryString>
	<field name="id" class="java.lang.String">
		<fieldDescription><![CDATA[]]></fieldDescription>
	</field>
	<field name="name" class="java.lang.String">
		<fieldDescription><![CDATA[]]></fieldDescription>
	</field>
	<field name="password" class="java.lang.String">
		<fieldDescription><![CDATA[]]></fieldDescription>
	</field>
	<variable name="count" class="java.math.BigDecimal" incrementType="Group" incrementGroup="countName" calculation="Count">
		<variableExpression><![CDATA[$F{name}]]></variableExpression>
	</variable>
	<group name="countName">
		<groupExpression><![CDATA[$F{name}]]></groupExpression>
	</group>
	<background>
		<band/>
	</background>
	<title>
		<band height="40">
			<staticText>
				<reportElement x="248" y="0" width="79" height="29"/>
				<textElement>
					<font size="18"/>
				</textElement>
				<text><![CDATA[用户信息]]></text>
			</staticText>
		</band>
	</title>
	<pageHeader>
		<band/>
	</pageHeader>
	<columnHeader>
		<band height="20">
			<staticText>
				<reportElement x="34" y="0" width="100" height="20"/>
				<textElement textAlignment="Center" verticalAlignment="Middle"/>
				<text><![CDATA[用户ID]]></text>
			</staticText>
			<staticText>
				<reportElement x="199" y="0" width="100" height="20"/>
				<textElement textAlignment="Center" verticalAlignment="Middle"/>
				<text><![CDATA[用户名]]></text>
			</staticText>
			<staticText>
				<reportElement x="394" y="0" width="100" height="20"/>
				<textElement textAlignment="Center" verticalAlignment="Middle"/>
				<text><![CDATA[密码]]></text>
			</staticText>
			<line>
				<reportElement x="172" y="0" width="1" height="20"/>
			</line>
			<line>
				<reportElement x="353" y="0" width="1" height="20"/>
			</line>
			<line>
				<reportElement x="0" y="-1" width="555" height="1"/>
			</line>
			<line>
				<reportElement x="0" y="0" width="1" height="20"/>
			</line>
			<line>
				<reportElement x="554" y="0" width="1" height="20"/>
			</line>
			<line>
				<reportElement x="0" y="19" width="555" height="1"/>
			</line>
		</band>
	</columnHeader>
	<detail>
		<band height="20">
			<textField>
				<reportElement x="34" y="0" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{id}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="199" y="0" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{name}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="394" y="0" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[$F{password}]]></textFieldExpression>
			</textField>
			<line>
				<reportElement x="0" y="19" width="555" height="1"/>
			</line>
			<line>
				<reportElement x="0" y="0" width="1" height="19"/>
			</line>
			<line>
				<reportElement x="172" y="0" width="1" height="19"/>
			</line>
			<line>
				<reportElement x="353" y="0" width="1" height="19"/>
			</line>
			<line>
				<reportElement x="554" y="0" width="1" height="19"/>
			</line>
		</band>
	</detail>
	<columnFooter>
		<band/>
	</columnFooter>
	<pageFooter>
		<band/>
	</pageFooter>
	<summary>
		<band height="31">
			<staticText>
				<reportElement x="316" y="11" width="51" height="20"/>
				<textElement/>
				<text><![CDATA[共有用户:]]></text>
			</staticText>
			<textField>
				<reportElement x="367" y="11" width="100" height="20"/>
				<textElement/>
				<textFieldExpression class="java.math.BigDecimal"><![CDATA[$V{count}]]></textFieldExpression>
			</textField>
		</band>
	</summary>
</jasperReport>

 

 

 数据库端使用的是sqlserver,大家可以根据自己需求自行配置。

另附简单demo一份。

8
2
分享到:
评论
11 楼 programwyh 2012-06-04  
jinyanhui2008 写道
programwyh 写道
我用java程序写的运用JasperReports,
但遇到导出PDF中文不显示问题,很苦恼,求帮助~~~

需要用的iText2.1.7.jar和iTextAsian.jar都已经放进lib了。。。

网上说导出PDF的时候,把要显示中文的组件的以下3个属性改了,我改了结果会报错:

pdfFontName="STSong-Light"
isPdfEmbeded="true"
pdfEncoding="UniGB-UCS2-H"

报的错误:could not load the following font:
pdfFontName="STSong-Light"
isPdfEmbeded="true"
pdfEncoding="UniGB-UCS2-H"

请博主帮助~~~~


貌似是没有字体吧?要加字库到你的应用目录下的


可是字体不是已经在iTextAsian.jar包里了吗。。。
10 楼 jinyanhui2008 2012-06-04  
programwyh 写道
我用java程序写的运用JasperReports,
但遇到导出PDF中文不显示问题,很苦恼,求帮助~~~

需要用的iText2.1.7.jar和iTextAsian.jar都已经放进lib了。。。

网上说导出PDF的时候,把要显示中文的组件的以下3个属性改了,我改了结果会报错:

pdfFontName="STSong-Light"
isPdfEmbeded="true"
pdfEncoding="UniGB-UCS2-H"

报的错误:could not load the following font:
pdfFontName="STSong-Light"
isPdfEmbeded="true"
pdfEncoding="UniGB-UCS2-H"

请博主帮助~~~~


貌似是没有字体吧?要加字库到你的应用目录下的
9 楼 programwyh 2012-05-30  
我用java程序写的运用JasperReports,
但遇到导出PDF中文不显示问题,很苦恼,求帮助~~~

需要用的iText2.1.7.jar和iTextAsian.jar都已经放进lib了。。。

网上说导出PDF的时候,把要显示中文的组件的以下3个属性改了,我改了结果会报错:

pdfFontName="STSong-Light"
isPdfEmbeded="true"
pdfEncoding="UniGB-UCS2-H"

报的错误:could not load the following font:
pdfFontName="STSong-Light"
isPdfEmbeded="true"
pdfEncoding="UniGB-UCS2-H"

请博主帮助~~~~

8 楼 jinyanhui2008 2009-05-14  
freedomodin 写道

感谢楼主,这里还有个问题请教,我在输出html的时候,文字的字体和字号都不对,请问怎么在代码里面设置字体和字号。

这个你需要去查询ireport的相关帮助信息了,他的功能还是很强大的。。。
7 楼 freedomodin 2009-05-13  
感谢楼主,这里还有个问题请教,我在输出html的时候,文字的字体和字号都不对,请问怎么在代码里面设置字体和字号。
6 楼 jiangsha 2009-04-24  
xuhbiao 写道

不错,学习了。。。JavaEye怎么没有收藏这个功能呢?

收藏就在下载下面的一行里啊,
5 楼 xuhbiao 2009-04-16  
不错,学习了。。。JavaEye怎么没有收藏这个功能呢?
4 楼 jinyanhui2008 2009-03-20  
javacool_zhou 写道

嘿嘿,有个可以run的小demo就ok了。。。。 期待中。。。。。。。。

其实这些代码直接拷贝进去就能跑了,也不复杂啊,如果一定要做个run的demo的话,也不难,抽空整一个吧。
3 楼 javacool_zhou 2009-03-19  
嘿嘿,有个可以run的小demo就ok了。。。。
期待中。。。。。。。。
2 楼 jinyanhui2008 2009-03-19  
rmn190 写道

现在很少见这样大块大块地在JSP里做Java操作的情况了. 楼主有没有现成的可运行小例子?

正常情况下这些代码拷贝到工程里面就可以运行的,这个例子是根据我们实际项目来做的,你可以稍加改动就能运行了
另外并不是我想在jsp中写这堆代码,因为我们的工程中使用的是flex,所以客户端没有相应的框架,需要用servlet来接收,后来想想干脆还是用jsp算了,图省事,如果将来flex可以解析pdf的时候我会考虑将这块代码封装到业务逻辑层里面去的。
1 楼 rmn190 2009-03-18  
现在很少见这样大块大块地在JSP里做Java操作的情况了.

楼主有没有现成的可运行小例子?

相关推荐

Global site tag (gtag.js) - Google Analytics