zoukankan      html  css  js  c++  java
  • 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(放入进去之后会出现蚂蚁图标);



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



    后台代码:TestServlet.java

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

    JDBC:

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


    执行效果:html数据



    原文地址:https://blog.csdn.net/u013378306/article/details/52412876
  • 相关阅读:
    python之numpy多维数组
    运用python绘图
    关于爬取babycenter.com A-Z为顺序的所有英文名及其详细属性
    Python 之列表切片的四大常用操作
    没点B树,怎么搞懂数据库索引底层原理(B+Tree)
    App弱网测试与常用模拟工具
    白盒测试理解与示例 与Jacoco
    APP弱网测试 抓包软件就能用于模拟弱网(Fiddler、Charles)
    获取系统属性值
    互联网常用架构-还需继续扩展学
  • 原文地址:https://www.cnblogs.com/jpfss/p/11121706.html
Copyright © 2011-2022 走看看