jasperReports 通过java导出各种格式报表,及javaweb项目整合显示各种报表


注意:编写此项目时,请先手动编写**.jrxml
 或者用IReport生成**.jrxml或**.jasper

注:java导出报表与web项目显示报表方法其实是相同的,只不过有一句代码不同,如下


  1. html.setParameter(JRHtmlExporterParameter.OUTPUT_FILE_NAME,"C:/Users/Administrator/Desktop/ireport/report1.html");//生成文件
  2. //html.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER,response.getWriter()); // web页面显示

maven依赖


  1. <!-- iReport JasperReports -->
  2. <dependency>
  3. <groupId>net.sf.jasperreports</groupId>
  4. <artifactId>jasperreports</artifactId>
  5. <version>5.6.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.codehaus.groovy</groupId>
  9. <artifactId>groovy-all</artifactId>
  10. <version>2.2.2</version>
  11. </dependency>

通过java代码生成各种格式报表文件

JDBC文件


  1. package com.hlzt.test;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.Statement;
  6. public class JDBC {
  7. public static String driver="com.mysql.jdbc.Driver";
  8. public static String url="jdbc:mysql://localhost:3306/senyuan1";
  9. public static String user="root";
  10. public static String pwd="123456";
  11. public static Connection conn=getConnection();
  12. public static Statement statement=getStatement();
  13. private static Connection getConnection(){
  14. if(conn==null){
  15. try{
  16. Class.forName(driver);
  17. conn=DriverManager.getConnection(url,user,pwd);
  18. }catch(Exception e){
  19. e.printStackTrace();
  20. }
  21. }
  22. return conn;
  23. }
  24. private static Statement getStatement(){
  25. if(statement==null){
  26. try{
  27. statement=conn.createStatement();
  28. }catch(Exception e){
  29. e.printStackTrace();
  30. }
  31. }
  32. return statement;
  33. }
  34. public static ResultSet getResultSet(String sql){
  35. ResultSet rs=null;
  36. try{
  37. rs=statement.executeQuery(sql);
  38. }catch(Exception e){
  39. e.printStackTrace();
  40. }
  41. return rs;
  42. }
  43. public static void closeAll(ResultSet rs,Statement st,Connection cn){
  44. try{
  45. if(rs!=null){
  46. rs.close();
  47. }
  48. if(st!=null){
  49. st.close();
  50. }
  51. if(cn!=null){
  52. cn.close();
  53. }
  54. }catch(Exception e){
  55. e.printStackTrace();
  56. }
  57. }
  58. }

生成 各种格式


  1. package com.hlzt.test;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. import javax.servlet.ServletContext;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import net.sf.jasperreports.engine.JRExporterParameter;
  13. import net.sf.jasperreports.engine.JasperCompileManager;
  14. import net.sf.jasperreports.engine.JasperFillManager;
  15. import net.sf.jasperreports.engine.JasperPrint;
  16. import net.sf.jasperreports.engine.JasperReport;
  17. import net.sf.jasperreports.engine.export.JRHtmlExporter;
  18. import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
  19. import net.sf.jasperreports.engine.util.JRLoader;
  20. @SuppressWarnings("deprecation")
  21. public class TestReport {
  22. public static void main(String[] args) {
  23. service();
  24. }
  25. //protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {\
  26. protected static void service(){
  27. try{
  28. //ServletContext context = this.getServletConfig().getServletContext();
  29. //JasperCompileManager 编译管理器
  30. //JasperFillManager 填充管理器
  31. //JRXmlLoader xml加载器
  32. //JasperPrintManager 打印管理器
  33. //JasperExportManager 导出管理器
  34. //JasperCompileManager.compileReportToFile(context.getRealPath("/reports/DbReport.jrxml"));//编译jrxml文件,生成jasper文件
  35. Map map=new HashMap();//参数map
  36. map.put("userName", "admin");
  37. //生成jrprint文件
  38. //JasperFillManager.fillReportToFile(context.getRealPath("/reports/DbReport.jasper"), map, JDBC.conn);
  39. File jasperFile=new File("C:/Users/Administrator/Desktop/ireport/report1.jasper");
  40. JasperReport jasperReport =(JasperReport)JRLoader.loadObject(jasperFile);
  41. JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map,JDBC.conn);
  42. File file=new File("C:/Users/Administrator/Desktop/ireport/report1.html");
  43. //生成html
  44. JRHtmlExporter html = new JRHtmlExporter();
  45. html.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
  46. html.setParameter(JRHtmlExporterParameter.OUTPUT_FILE_NAME,"C:/Users/Administrator/Desktop/ireport/report1.html");//生成文件
  47. //html.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER,response.getWriter()); // web页面显示
  48. html.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,Boolean.FALSE);
  49. html.setParameter(JRExporterParameter.CHARACTER_ENCODING, "utf-8");
  50. html.exportReport();
  51. //生成excel
  52. /*
  53. JRXlsExporter xls=new JRXlsExporter();
  54. */
  55. //生成pdf
  56. /*
  57. JRPdfExporter pdf = new JRPdfExporter();
  58. */
  59. }catch(Exception e){
  60. e.printStackTrace();
  61. }
  62. }
  63. }

与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(放入进去之后会出现蚂蚁图标);

jasperReports 通过java导出各种格式报表,及javaweb项目整合显示各种报表

jrxml文件代码,此代码是xml格式文件,可以自己手写,也可以安装 iReport设计编译成jasper文件,为了入门下面纯手写

DbReport.jrxml:

[html] view
plain
 copy
  1. <span style="font-size:14px;"><?xml version="1.0" encoding="UTF-8" ?>
  2. <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports
  5. http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="DbReport" >
  6. <!-- jasperReport标签中name="DbReport"需要对应外面文件名, $P{}为填充参数,$V{}为值 ,$F{}为查询值或者为Jr数据-->
  7. <!-- 页面样式标签 --属性:
  8. forecolor(前景色,就是文本)
  9. backcolor(背景色)
  10. hAlign(水平位置Center, Justified, Left, Right)
  11. vAlign(垂直位置Bottom, Middle, Top)
  12. border(边框1Point, 2Point, 4Point, Dotted, None, Thin)
  13. borderColor(边框颜色)
  14. fontName(字体)
  15. fontSize(字体大小)
  16. isBold,isItalic,IsUnderline,isStrikeThrough(粗体,斜体,下画线,..)
  17. lineSpacing(1_1_2, Double, Single行间距)
  18. rotation(旋转,Left, None, Right,转的是90度)
  19. isStyledText(指示这个Element是否用Style,true,false)
  20. isDefault(说明这个样式是否默认样式)
  21. -->
  22. <style name="pageHeader" forecolor="#FFFFFF" backcolor="#333333"/>
  23. <!-- 参数标签 -->
  24. <parameter name="userName" class="java.lang.String"/>
  25. <!-- 查询语句标签 -->
  26. <queryString>
  27. <![CDATA[
  28. select id,user_name as name,email,qq from user where user_name=$P{userName}
  29. ]]>
  30. </queryString>
  31. <!-- 显示字段标签 -->
  32. <field name="id" class="java.lang.Integer" />
  33. <field name="name" class="java.lang.String" />
  34. <field name="email" class="java.lang.String" />
  35. <field name="qq" class="java.lang.String" />
  36. <pageHeader>
  37. <band height="30">
  38. <staticText>
  39. <reportElement style="pageHeader"  x="0" y="5" width="55" height="15"/>
  40. <textElement textAlignment="Center"/>
  41. <text><![CDATA[ID]]></text>
  42. </staticText>
  43. <staticText>
  44. <reportElement style="pageHeader"  x="55" y="5" width="205" height="15"/>
  45. <text><![CDATA[Name]]></text>
  46. </staticText>
  47. <staticText>
  48. <reportElement style="pageHeader"  x="160" y="5" width="255" height="15"/>
  49. <text><![CDATA[Email]]></text>
  50. </staticText>
  51. <staticText>
  52. <reportElement style="pageHeader"  x="260" y="5" width="255" height="15"/>
  53. <text><![CDATA[QQ]]></text>
  54. </staticText>
  55. </band>
  56. </pageHeader>
  57. <!-- 显示内容-->
  58. <detail>
  59. <band height="20">
  60. <textField>
  61. <reportElement x="0" y="4" width="50" height="15"/>
  62. <textElement textAlignment="Right"/>
  63. <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
  64. </textField>
  65. <textField isStretchWithOverflow="true">
  66. <reportElement positionType="Float" x="55" y="4" width="100" height="15"/>
  67. <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
  68. </textField>
  69. <textField isStretchWithOverflow="true">
  70. <reportElement positionType="Float" x="160" y="4" width="100" height="15"/>
  71. <textFieldExpression><![CDATA[$F{email}]]></textFieldExpression>
  72. </textField>
  73. <textField isStretchWithOverflow="true">
  74. <reportElement positionType="Float" x="260" y="4" width="255" height="15"/>
  75. <textFieldExpression><![CDATA[$F{qq}]]></textFieldExpression>
  76. </textField>
  77. <line>
  78. <reportElement positionType="Float" x="0" y="19" width="515" height="1" forecolor="#808080"/>
  79. </line>
  80. </band>
  81. </detail>
  82. </jasperReport>
  83. </span>

后台代码:TestServlet.java

[java] view
plain
 copy
  1. <span style="font-size:14px;">package servlets;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.sql.ResultSet;
  6. import java.util.HashMap;
  7. import java.util.Map;
  8. import javax.servlet.ServletContext;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import util.JDBC;
  14. import net.sf.jasperreports.engine.JRDataSource;
  15. import net.sf.jasperreports.engine.JRExporterParameter;
  16. import net.sf.jasperreports.engine.JRResultSetDataSource;
  17. import net.sf.jasperreports.engine.JasperCompileManager;
  18. import net.sf.jasperreports.engine.JasperExportManager;
  19. import net.sf.jasperreports.engine.JasperFillManager;
  20. import net.sf.jasperreports.engine.JasperPrint;
  21. import net.sf.jasperreports.engine.JasperReport;
  22. import net.sf.jasperreports.engine.JasperRunManager;
  23. import net.sf.jasperreports.engine.data.JRMapArrayDataSource;
  24. import net.sf.jasperreports.engine.export.JRHtmlExporter;
  25. import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
  26. import net.sf.jasperreports.engine.export.JRPdfExporter;
  27. import net.sf.jasperreports.engine.export.JRXlsExporter;
  28. import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
  29. import net.sf.jasperreports.engine.util.JRLoader;
  30. import net.sf.jasperreports.view.JasperViewer;
  31. public class TestServlet extends HttpServlet {
  32. @Override
  33. protected void service(HttpServletRequest request, HttpServletResponse response)
  34. throws ServletException, IOException {
  35. try{
  36. ServletContext context = this.getServletConfig().getServletContext();
  37. //JasperCompileManager 编译管理器
  38. //JasperFillManager 填充管理器
  39. //JRXmlLoader xml加载器
  40. //JasperPrintManager 打印管理器
  41. //JasperExportManager 导出管理器
  42. //JasperRunManager 运行管理器
  43. JasperCompileManager.compileReportToFile(context.getRealPath("/reports/DbReport.jrxml"));//编译jrxml文件,生成jasper文件
  44. Map map=new HashMap();//参数map
  45. map.put("userName", "admin");
  46. //生成jrprint文件
  47. //JasperFillManager.fillReportToFile(context.getRealPath("/reports/DbReport.jasper"), map, JDBC.conn);
  48. File jasperFile=new File(context.getRealPath("/reports/DbReport.jasper"));
  49. JasperReport jasperReport =(JasperReport)JRLoader.loadObject(jasperFile);
  50. JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, map,JDBC.conn);
  51. //将查询的数据填充到报表中
  52. //String sql="select id,user_name as name,email,qq from user";
  53. //ResultSet rs=JDBC.getResultSet(sql);
  54. //JRResultSetDataSource jr=new JRResultSetDataSource(rs);
  55. //JasperFillManager.fillReportToFile(context.getRealPath("/reports/DbReport.jasper"), map, jr);
  56. //JDBC.closeAll(rs, JDBC.statement, null);//关闭数据连接
  57. //JasperRunManager.runReportToHtmlFile(context.getRealPath("/reports/DbReport.jasper"), map, JDBC.conn);
  58. //JasperRunManager.runReportToHtmlFile(context.getRealPath("/reports/DbReport.jasper"), map, jr);
  59. //生成html文件
  60. //JasperRunManager.runReportToHtmlFile(context.getRealPath("/reports/DbReport.jasper"), "E:/test.html", map, JDBC.conn);
  61. //InputStream  inputStream=getServletConfig().getServletContext().getResourceAsStream(context.getRealPath("/reports/DbReport.jasper"));
  62. //JasperRunManager.runReportToPdfStream(inputStream, response.getOutputStream(), map, jr);
  63. //-----以map数组为数据源,生成html文件
  64. JasperRunManager.runReportToHtmlFile(context.getRealPath("/reports/DbReport.jasper"), "E:/test2.html", map, getReportDataSource());
  65. //生成html数据
  66. /*
  67. JRHtmlExporter html = new JRHtmlExporter();
  68. html.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
  69. html.setParameter(JRHtmlExporterParameter.OUTPUT_WRITER,response.getWriter());
  70. html.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,Boolean.FALSE);
  71. html.setParameter(JRExporterParameter.CHARACTER_ENCODING, "utf-8");
  72. html.exportReport();
  73. */
  74. //生成excel
  75. /*
  76. JRXlsExporter xls=new JRXlsExporter();
  77. xls.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
  78. xls.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, response.getOutputStream());
  79. xls.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
  80. xls.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
  81. response.setHeader("Content-Disposition", "attachment;filename=first.xls");
  82. response.setContentType("application/vnd_ms-excel");
  83. xls.exportReport();
  84. */
  85. //生成pdf
  86. /*
  87. JRPdfExporter pdf = new JRPdfExporter();
  88. pdf.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
  89. pdf.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
  90. response.setHeader("Content-Disposition", "attachment;filename=first.pdf");
  91. response.setContentType("application/pdf");
  92. response.setCharacterEncoding("UTF-8");
  93. pdf.exportReport();
  94. */
  95. }catch(Exception e){
  96. e.printStackTrace();
  97. }
  98. }
  99. private JRDataSource getReportDataSource(){
  100. //new JRMapArrayDataSource(getMaparray());这里也可以传自定义对象数组,对象属性字段必须对应DbReport.jrxml中显示数据字段
  101. JRMapArrayDataSource dataSource=new JRMapArrayDataSource(getMaparray());
  102. return dataSource;
  103. }
  104. private Map[] getMaparray(){
  105. //map key键必须对应DbReport.jrxml中显示数据字段
  106. Map map1=new HashMap();
  107. map1.put("id", 1);
  108. map1.put("name", "aaa");
  109. map1.put("email", "111@qq.com");
  110. map1.put("qq", "111");
  111. Map map2=new HashMap();
  112. map2.put("id", 2);
  113. map2.put("name", "bbb");
  114. map2.put("email", "222@qq.com");
  115. map2.put("qq", "222");
  116. Map map3=new HashMap();
  117. map3.put("id", 3);
  118. map3.put("name", "ccc");
  119. map3.put("email", "333@qq.com");
  120. map3.put("qq", "333");
  121. Map[] mapArray=new Map[3];
  122. mapArray[0]=map1;
  123. mapArray[1]=map2;
  124. mapArray[2]=map3;
  125. return mapArray;
  126. }
  127. }
  128. </span>

JDBC:

[java] view
plain
 copy
  1. <span style="font-size:14px;">package util;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.Statement;
  6. public class JDBC {
  7. public static String driver="com.mysql.jdbc.Driver";
  8. public static String url="jdbc:mysql://localhost:3306/myapp";
  9. public static String user="root";
  10. public static String pwd="root";
  11. public static Connection conn=getConnection();
  12. public static Statement statement=getStatement();
  13. private static Connection getConnection(){
  14. if(conn==null){
  15. try{
  16. Class.forName(driver);
  17. conn=DriverManager.getConnection(url,user,pwd);
  18. }catch(Exception e){
  19. e.printStackTrace();
  20. }
  21. }
  22. return conn;
  23. }
  24. private static Statement getStatement(){
  25. if(statement==null){
  26. try{
  27. statement=conn.createStatement();
  28. }catch(Exception e){
  29. e.printStackTrace();
  30. }
  31. }
  32. return statement;
  33. }
  34. public static ResultSet getResultSet(String sql){
  35. ResultSet rs=null;
  36. try{
  37. rs=statement.executeQuery(sql);
  38. }catch(Exception e){
  39. e.printStackTrace();
  40. }
  41. return rs;
  42. }
  43. public static void closeAll(ResultSet rs,Statement st,Connection cn){
  44. try{
  45. if(rs!=null){
  46. rs.close();
  47. }
  48. if(st!=null){
  49. st.close();
  50. }
  51. if(cn!=null){
  52. cn.close();
  53. }
  54. }catch(Exception e){
  55. e.printStackTrace();
  56. }
  57. }
  58. }
  59. </span>

执行效果:html数据

jasperReports 通过java导出各种格式报表,及javaweb项目整合显示各种报表

原文地址:https://blog.csdn.net/u013378306/article/details/52412876

上一篇:SpringBoot使用JSP(官网Demo)


下一篇:windows转mac-开发环境搭建(一):需要搭建的环境及安装的工具