注意:编写此项目时,请先手动编写**.jrxml
或者用IReport生成**.jrxml或**.jasper
注:java导出报表与web项目显示报表方法其实是相同的,只不过有一句代码不同,如下
-
html.setParameter(JRHtmlExporterParameter.OUTPUT_FILE_NAME,"C:/Users/Administrator/Desktop/ireport/report1.html");//生成文件
-
//html.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER,response.getWriter()); // web页面显示
maven依赖
-
<!-- iReport JasperReports -->
-
<dependency>
-
<groupId>net.sf.jasperreports</groupId>
-
<artifactId>jasperreports</artifactId>
-
<version>5.6.0</version>
-
</dependency>
-
<dependency>
-
<groupId>org.codehaus.groovy</groupId>
-
<artifactId>groovy-all</artifactId>
-
<version>2.2.2</version>
-
</dependency>
通过java代码生成各种格式报表文件
JDBC文件
-
package com.hlzt.test;
-
-
import java.sql.Connection;
-
import java.sql.DriverManager;
-
import java.sql.ResultSet;
-
import java.sql.Statement;
-
-
public class JDBC {
-
public static String driver="com.mysql.jdbc.Driver";
-
public static String url="jdbc:mysql://localhost:3306/senyuan1";
-
public static String user="root";
-
public static String pwd="123456";
-
public static Connection conn=getConnection();
-
public static Statement statement=getStatement();
-
-
private static Connection getConnection(){
-
if(conn==null){
-
try{
-
Class.forName(driver);
-
conn=DriverManager.getConnection(url,user,pwd);
-
}catch(Exception e){
-
e.printStackTrace();
-
}
-
}
-
return conn;
-
}
-
private static Statement getStatement(){
-
if(statement==null){
-
try{
-
statement=conn.createStatement();
-
}catch(Exception e){
-
e.printStackTrace();
-
}
-
}
-
return statement;
-
}
-
public static ResultSet getResultSet(String sql){
-
ResultSet rs=null;
-
try{
-
rs=statement.executeQuery(sql);
-
}catch(Exception e){
-
e.printStackTrace();
-
}
-
return rs;
-
}
-
public static void closeAll(ResultSet rs,Statement st,Connection cn){
-
try{
-
if(rs!=null){
-
rs.close();
-
}
-
if(st!=null){
-
st.close();
-
}
-
if(cn!=null){
-
cn.close();
-
}
-
}catch(Exception e){
-
e.printStackTrace();
-
}
-
}
-
}
生成 各种格式
-
package com.hlzt.test;
-
import java.io.File;
-
import java.io.IOException;
-
import java.io.InputStream;
-
import java.util.HashMap;
-
import java.util.Map;
-
-
import javax.servlet.ServletContext;
-
import javax.servlet.ServletException;
-
import javax.servlet.http.HttpServlet;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
import net.sf.jasperreports.engine.JRExporterParameter;
-
import net.sf.jasperreports.engine.JasperCompileManager;
-
import net.sf.jasperreports.engine.JasperFillManager;
-
import net.sf.jasperreports.engine.JasperPrint;
-
import net.sf.jasperreports.engine.JasperReport;
-
import net.sf.jasperreports.engine.export.JRHtmlExporter;
-
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
-
import net.sf.jasperreports.engine.util.JRLoader;
-
@SuppressWarnings("deprecation")
-
public class TestReport {
-
-
public static void main(String[] args) {
-
service();
-
}
-
//protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {\
-
protected static void service(){
-
try{
-
//ServletContext context = this.getServletConfig().getServletContext();
-
-
//JasperCompileManager 编译管理器
-
//JasperFillManager 填充管理器
-
//JRXmlLoader xml加载器
-
//JasperPrintManager 打印管理器
-
//JasperExportManager 导出管理器
-
-
//JasperCompileManager.compileReportToFile(context.getRealPath("/reports/DbReport.jrxml"));//编译jrxml文件,生成jasper文件
-
-
Map map=new HashMap();//参数map
-
map.put("userName", "admin");
-
-
//生成jrprint文件
-
//JasperFillManager.fillReportToFile(context.getRealPath("/reports/DbReport.jasper"), map, JDBC.conn);
-
-
-
File jasperFile=new File("C:/Users/Administrator/Desktop/ireport/report1.jasper");
-
JasperReport jasperReport =(JasperReport)JRLoader.loadObject(jasperFile);
-
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map,JDBC.conn);
-
File file=new File("C:/Users/Administrator/Desktop/ireport/report1.html");
-
//生成html
-
JRHtmlExporter html = new JRHtmlExporter();
-
html.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
-
html.setParameter(JRHtmlExporterParameter.OUTPUT_FILE_NAME,"C:/Users/Administrator/Desktop/ireport/report1.html");//生成文件
-
//html.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER,response.getWriter()); // web页面显示
-
html.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,Boolean.FALSE);
-
html.setParameter(JRExporterParameter.CHARACTER_ENCODING, "utf-8");
-
html.exportReport();
-
//生成excel
-
/*
-
JRXlsExporter xls=new JRXlsExporter();
-
*/
-
//生成pdf
-
/*
-
JRPdfExporter pdf = new JRPdfExporter();
-
*/
-
}catch(Exception e){
-
e.printStackTrace();
-
}
-
}
-
}
与javaweb整合
本文用的是JasperReport最新版本6.0
JasperReport官网:community.jaspersoft.com
web开发建议下载JasperReports library --> jasperreports-xxx-project 里面包含demo以及api
项目结构:
jar包:新手可以把下载下来的所有jar包都放进去,熟练之后可以根据自己所需加入相关jar包
WebRoot下:新建reports文件夹,用来存放jrxml、jasper文件;build.xml(放入进去之后会出现蚂蚁图标);
jrxml文件代码,此代码是xml格式文件,可以自己手写,也可以安装 iReport设计编译成jasper文件,为了入门下面纯手写
DbReport.jrxml:
[html] view
plain copy
plain copy
- <span style="font-size:14px;"><?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="DbReport" >
- <!-- jasperReport标签中name="DbReport"需要对应外面文件名, $P{}为填充参数,$V{}为值 ,$F{}为查询值或者为Jr数据-->
- <!-- 页面样式标签 --属性:
- forecolor(前景色,就是文本)
- backcolor(背景色)
- hAlign(水平位置Center, Justified, Left, Right)
- vAlign(垂直位置Bottom, Middle, Top)
- border(边框1Point, 2Point, 4Point, Dotted, None, Thin)
- borderColor(边框颜色)
- fontName(字体)
- fontSize(字体大小)
- isBold,isItalic,IsUnderline,isStrikeThrough(粗体,斜体,下画线,..)
- lineSpacing(1_1_2, Double, Single行间距)
- rotation(旋转,Left, None, Right,转的是90度)
- isStyledText(指示这个Element是否用Style,true,false)
- isDefault(说明这个样式是否默认样式)
- -->
- <style name="pageHeader" forecolor="#FFFFFF" backcolor="#333333"/>
- <!-- 参数标签 -->
- <parameter name="userName" class="java.lang.String"/>
- <!-- 查询语句标签 -->
- <queryString>
- <![CDATA[
- select id,user_name as name,email,qq from user where user_name=$P{userName}
- ]]>
- </queryString>
- <!-- 显示字段标签 -->
- <field name="id" class="java.lang.Integer" />
- <field name="name" class="java.lang.String" />
- <field name="email" class="java.lang.String" />
- <field name="qq" class="java.lang.String" />
- <pageHeader>
- <band height="30">
- <staticText>
- <reportElement style="pageHeader" x="0" y="5" width="55" height="15"/>
- <textElement textAlignment="Center"/>
- <text><![CDATA[ID]]></text>
- </staticText>
- <staticText>
- <reportElement style="pageHeader" x="55" y="5" width="205" height="15"/>
- <text><![CDATA[Name]]></text>
- </staticText>
- <staticText>
- <reportElement style="pageHeader" x="160" y="5" width="255" height="15"/>
- <text><![CDATA[Email]]></text>
- </staticText>
- <staticText>
- <reportElement style="pageHeader" x="260" y="5" width="255" height="15"/>
- <text><![CDATA[QQ]]></text>
- </staticText>
- </band>
- </pageHeader>
- <!-- 显示内容-->
- <detail>
- <band height="20">
- <textField>
- <reportElement x="0" y="4" width="50" height="15"/>
- <textElement textAlignment="Right"/>
- <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
- </textField>
- <textField isStretchWithOverflow="true">
- <reportElement positionType="Float" x="55" y="4" width="100" height="15"/>
- <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
- </textField>
- <textField isStretchWithOverflow="true">
- <reportElement positionType="Float" x="160" y="4" width="100" height="15"/>
- <textFieldExpression><![CDATA[$F{email}]]></textFieldExpression>
- </textField>
- <textField isStretchWithOverflow="true">
- <reportElement positionType="Float" x="260" y="4" width="255" height="15"/>
- <textFieldExpression><![CDATA[$F{qq}]]></textFieldExpression>
- </textField>
- <line>
- <reportElement positionType="Float" x="0" y="19" width="515" height="1" forecolor="#808080"/>
- </line>
- </band>
- </detail>
- </jasperReport>
- </span>
后台代码:TestServlet.java
[java] view
plain copy
plain copy
- <span style="font-size:14px;">package servlets;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.sql.ResultSet;
- import java.util.HashMap;
- import java.util.Map;
- import javax.servlet.ServletContext;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import util.JDBC;
- import net.sf.jasperreports.engine.JRDataSource;
- import net.sf.jasperreports.engine.JRExporterParameter;
- import net.sf.jasperreports.engine.JRResultSetDataSource;
- import net.sf.jasperreports.engine.JasperCompileManager;
- import net.sf.jasperreports.engine.JasperExportManager;
- import net.sf.jasperreports.engine.JasperFillManager;
- import net.sf.jasperreports.engine.JasperPrint;
- import net.sf.jasperreports.engine.JasperReport;
- import net.sf.jasperreports.engine.JasperRunManager;
- import net.sf.jasperreports.engine.data.JRMapArrayDataSource;
- import net.sf.jasperreports.engine.export.JRHtmlExporter;
- import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
- import net.sf.jasperreports.engine.export.JRPdfExporter;
- import net.sf.jasperreports.engine.export.JRXlsExporter;
- import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
- import net.sf.jasperreports.engine.util.JRLoader;
- import net.sf.jasperreports.view.JasperViewer;
- public class TestServlet extends HttpServlet {
- @Override
- protected void service(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- try{
- ServletContext context = this.getServletConfig().getServletContext();
- //JasperCompileManager 编译管理器
- //JasperFillManager 填充管理器
- //JRXmlLoader xml加载器
- //JasperPrintManager 打印管理器
- //JasperExportManager 导出管理器
- //JasperRunManager 运行管理器
- JasperCompileManager.compileReportToFile(context.getRealPath("/reports/DbReport.jrxml"));//编译jrxml文件,生成jasper文件
- Map map=new HashMap();//参数map
- map.put("userName", "admin");
- //生成jrprint文件
- //JasperFillManager.fillReportToFile(context.getRealPath("/reports/DbReport.jasper"), map, JDBC.conn);
- File jasperFile=new File(context.getRealPath("/reports/DbReport.jasper"));
- JasperReport jasperReport =(JasperReport)JRLoader.loadObject(jasperFile);
- JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map,JDBC.conn);
- //将查询的数据填充到报表中
- //String sql="select id,user_name as name,email,qq from user";
- //ResultSet rs=JDBC.getResultSet(sql);
- //JRResultSetDataSource jr=new JRResultSetDataSource(rs);
- //JasperFillManager.fillReportToFile(context.getRealPath("/reports/DbReport.jasper"), map, jr);
- //JDBC.closeAll(rs, JDBC.statement, null);//关闭数据连接
- //JasperRunManager.runReportToHtmlFile(context.getRealPath("/reports/DbReport.jasper"), map, JDBC.conn);
- //JasperRunManager.runReportToHtmlFile(context.getRealPath("/reports/DbReport.jasper"), map, jr);
- //生成html文件
- //JasperRunManager.runReportToHtmlFile(context.getRealPath("/reports/DbReport.jasper"), "E:/test.html", map, JDBC.conn);
- //InputStream inputStream=getServletConfig().getServletContext().getResourceAsStream(context.getRealPath("/reports/DbReport.jasper"));
- //JasperRunManager.runReportToPdfStream(inputStream, response.getOutputStream(), map, jr);
- //-----以map数组为数据源,生成html文件
- JasperRunManager.runReportToHtmlFile(context.getRealPath("/reports/DbReport.jasper"), "E:/test2.html", map, getReportDataSource());
- //生成html数据
- /*
- JRHtmlExporter html = new JRHtmlExporter();
- html.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
- html.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER,response.getWriter());
- html.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,Boolean.FALSE);
- html.setParameter(JRExporterParameter.CHARACTER_ENCODING, "utf-8");
- html.exportReport();
- */
- //生成excel
- /*
- JRXlsExporter xls=new JRXlsExporter();
- xls.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
- xls.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, response.getOutputStream());
- xls.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
- xls.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
- response.setHeader("Content-Disposition", "attachment;filename=first.xls");
- response.setContentType("application/vnd_ms-excel");
- xls.exportReport();
- */
- //生成pdf
- /*
- JRPdfExporter pdf = new JRPdfExporter();
- pdf.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
- pdf.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
- response.setHeader("Content-Disposition", "attachment;filename=first.pdf");
- response.setContentType("application/pdf");
- response.setCharacterEncoding("UTF-8");
- pdf.exportReport();
- */
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- private JRDataSource getReportDataSource(){
- //new JRMapArrayDataSource(getMaparray());这里也可以传自定义对象数组,对象属性字段必须对应DbReport.jrxml中显示数据字段
- JRMapArrayDataSource dataSource=new JRMapArrayDataSource(getMaparray());
- return dataSource;
- }
- private Map[] getMaparray(){
- //map key键必须对应DbReport.jrxml中显示数据字段
- Map map1=new HashMap();
- map1.put("id", 1);
- map1.put("name", "aaa");
- map1.put("email", "111@qq.com");
- map1.put("qq", "111");
- Map map2=new HashMap();
- map2.put("id", 2);
- map2.put("name", "bbb");
- map2.put("email", "222@qq.com");
- map2.put("qq", "222");
- Map map3=new HashMap();
- map3.put("id", 3);
- map3.put("name", "ccc");
- map3.put("email", "333@qq.com");
- map3.put("qq", "333");
- Map[] mapArray=new Map[3];
- mapArray[0]=map1;
- mapArray[1]=map2;
- mapArray[2]=map3;
- return mapArray;
- }
- }
- </span>
JDBC:
[java] view
plain copy
plain copy
- <span style="font-size:14px;">package util;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.Statement;
- public class JDBC {
- public static String driver="com.mysql.jdbc.Driver";
- public static String url="jdbc:mysql://localhost:3306/myapp";
- public static String user="root";
- public static String pwd="root";
- public static Connection conn=getConnection();
- public static Statement statement=getStatement();
- private static Connection getConnection(){
- if(conn==null){
- try{
- Class.forName(driver);
- conn=DriverManager.getConnection(url,user,pwd);
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- return conn;
- }
- private static Statement getStatement(){
- if(statement==null){
- try{
- statement=conn.createStatement();
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- return statement;
- }
- public static ResultSet getResultSet(String sql){
- ResultSet rs=null;
- try{
- rs=statement.executeQuery(sql);
- }catch(Exception e){
- e.printStackTrace();
- }
- return rs;
- }
- public static void closeAll(ResultSet rs,Statement st,Connection cn){
- try{
- if(rs!=null){
- rs.close();
- }
- if(st!=null){
- st.close();
- }
- if(cn!=null){
- cn.close();
- }
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- </span>
执行效果:html数据
原文地址:https://blog.csdn.net/u013378306/article/details/52412876