使用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一份。
上一篇: Flex初体验
下一篇: grafana 做业务数据分析