你的位置:首页 > Java教程

[Java教程]jasperreports+ireport制作报表笔记


一. 安装ant  

  1. 解压apache-ant-1.9.4-bin到任意地方  

  2. 配置环境变量ANT_HOME为apache-ant-1.9.4-bin解压后的目录地址,如D:\Download\apache-ant-1.9.4  

  3. 在环境变量CLASSPATH中加入%ANT_HOME%\lib;  

  4. 在环境变量Path中加入%ANT_HOME%\bin;  

  5. 在cmd下测试ant是否安装正确,命令:ant -version     安装成功显示ant的版本号,出错,自己网上查

 

二. 安装iReport,制作报表的工具  

  1. 直接双击iReport-5.6.0-windows-installer.exe进行安装

 

三. jasperreports源码与例子  

  1. 解压jasperreports-5.6.0-project.zip  

  2. 在含有build.

  3. /jasperreports-5.6.0/src下是源码,可在/jasperreports-5.6.0/目录下执行ant jar来编译源代码,

    最后在/jasperreports-5.6.0/dist/下生成jasperreports-5.6.0.jar包

  4. /jasperreports-5.6.0/demo/samples/下是实例  

  5. /jasperreports-5.6.0/demo/samples/webapp/下是标准的实例,可在其目录下执行ant war命令生成war包,可在tomcat下直接部署运行  

 

四. 制作一张报表  

      iReport设计报表应注意:在含有中文的地方,设置如下,防止pdf导出中文无法显示:    

      Font  name:    宋体 (中文字体)        

      PDF font name:   STSong-Light        

      PDF  Encoding:  UniGB-UCS2-H(Chinese Siplified)        

      PDF   Embeded: √

 

五. 报表在项目中的应用  

  1. 将制作好的报表(以jr

  2. 添加报表的数据源类,如:

    数据源接口BaseJRDataSource.java  

1 import java.util.Map;2 3 import net.sf.jasperreports.engine.JRDataSource;4 5 public interface BaseJRDataSource extends JRDataSource{6   public JRDataSource getInstance(Map parameters);7   public Map<String,Object> getReportParams(Map parameters);8 }

View Code

    具体报表的数据源类,如:

 1 import java.util.ArrayList; 2 import java.util.List; 3 import java.util.Map; 4  5 import net.sf.jasperreports.engine.JRDataSource; 6 import net.sf.jasperreports.engine.JRException; 7 import net.sf.jasperreports.engine.JRField; 8  9 10 public class ×××DataSource implements BaseJRDataSource{11   12   private List data = new ArrayList();13   private int index = -1;14 15   public ×××DataSource(){16     // 注入spring的bean类17   }18   19   /**20    * 判断报表是否有下一页21    * @return22   */23   @Override24   public boolean next() throws JRException{25     index++;26     return (index < data.size());27   }28   29   /**30    * 根据报表字段的名称,格式化字段的值31    * @param field 报表字段32    * @return33   */34   @Override35   public Object getFieldValue(JRField field) throws JRException{36     Object value = null;37     String fieldName = field.getName();38     if ("rownum".equals(fieldName)){39       value = index+1;40     }41     return value;42   }43   44   /**45    * 返回数据源实例46    * @param parameters 参数集47    * @return48   */49   @Override50   public JRDataSource getInstance(Map parameters){51     // 根据参数,取得报表要展示的数据52     data = ×××;53     index = -1;54     return this;55   }56   57   /**58    * 返回整合后的查询参数59    * @param parameters 参数集60    * @return61   */62   @Override63   public Map<String, Object> getReportParams(Map parameters) {64     return parameters;65   }66 67 }

View Code

  3. 在spring的配置文件application.

  4. 报表显示页面showReport.jsp,打印控件采用jatoolsPrinter.cab,需要tomcat服务以进程的方式启动 

 1 <%@ page contentType="text/html; charset=gb2312" language="java" %> 2  3 <%@ page errorPage="error.jsp" %> 4 <!-- spring服务定位器,可在任何地方取得bean --> 5 <%@ page import="com.×××.×××.ServiceLocator" %> 6 <%@ page import="com.×××.×××.datasource.BaseJRDataSource" %> 7 <%@ page import="net.sf.jasperreports.engine.*" %> 8 <%@ page import="net.sf.jasperreports.engine.util.*" %> 9 <%@ page import="net.sf.jasperreports.engine.export.*" %> 10 <%@ page import="net.sf.jasperreports.j2ee.servlets.*" %> 11 <%@ page import="java.util.*" %> 12 <%@ page import="java.io.*" %> 13 <%@ page import="net.sf.json.JSONObject" %> 14 <% 15   request.setCharacterEncoding("UTF-8"); 16   String report = request.getParameter("jasper"); 17   String dataSource = request.getParameter("ds"); 18   String args = request.getParameter("args"); 19   String fileName = request.getParameter("fileName"); 20   Map parameters = new HashMap(); 21    22   JSONObject jsonMap = JSONObject.fromObject(args);  23   Iterator<String> it = jsonMap.keys();  24   while(it.hasNext()) {  25     String key = (String)it.next();   26     parameters.put(key, jsonMap.get(key)); 27   }  28  29   String appmap = request.getContextPath(); 30  31   File reportFile = new File(application.getRealPath("/reportFiles/"+report+".jasper")); 32   if (!reportFile.exists()){ 33     JasperCompileManager.compileReportToFile(application.getRealPath("/reportFiles/"+report+".jr")); 34     reportFile = new File(application.getRealPath("/reportFiles/"+report+".jasper")); 35   } 36  37   JasperReport jasperReport = (JasperReport)JRLoader.loadObjectFromFile(reportFile.getPath()); 38   BaseJRDataSource baseJRDataSource=  ((BaseJRDataSource)ServiceLocator.getService(dataSource)); 39   JRDataSource jRDataSource = baseJRDataSource.getInstance(parameters); 40   JasperPrint jasperPrint =  41       JasperFillManager.fillReport( 42         jasperReport,  43         baseJRDataSource.getReportParams(parameters),  44         jRDataSource 45       ); 46    47   session.setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint); 48    49   int pageIndex = 0; 50   int lastPageIndex = 0; 51   if (jasperPrint.getPages() != null){ 52     lastPageIndex = jasperPrint.getPages().size() - 1; 53   } 54  55   String pageStr = request.getParameter("page"); 56   try{ 57     pageIndex = Integer.parseInt(pageStr); 58   } 59   catch(Exception e){} 60    61   if (pageIndex < 0){ 62     pageIndex = 0; 63   } 64  65   if (pageIndex > lastPageIndex){ 66     pageIndex = lastPageIndex; 67   } 68    69   HtmlExporter exporter = new HtmlExporter();   70   StringBuffer sbuffer = new StringBuffer(); 71  72   exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); 73   exporter.setParameter(JRExporterParameter.OUTPUT_STRING_BUFFER, sbuffer); 74   exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "../servlets/image?image="); 75   //exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(pageIndex)); 76   exporter.setParameter(JRHtmlExporterParameter.HTML_HEADER, ""); 77   exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, ""); 78   exporter.setParameter(JRHtmlExporterParameter.HTML_FOOTER, ""); 79  80   exporter.exportReport(); 81 %> 82 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 83 <html> 84 <head> 85  <title></title> 86  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 87  <style type="text/css"> 88   a {text-decoration: none} 89  </style> 90  <OBJECT ID="jatoolsPrinter" CLASSID="CLSID:B43D3361-D075-4BE2-87FE-057188254255" codebase="jatoolsPrinter.cab#version=5,7,0,0"></OBJECT> 91 </head> 92 <body topmargin=0 leftmargin=0 rightmargin=0 bottomMargin=0> 93 <table id=titleTable width=100% cellspacing=0 cellpadding=0 border=0 ><tr> 94   <td height="25" width=100% valign="middle" style="font-size:13px" background="toolbar-bg.gif"> 95     <table width="100%"> 96       <tr >         97         <td width="100%" align="right" valign="middle"  style="font-size:12px; line-height:12px; margin:3px 0 0 0 ;" >&nbsp; 98         <span style=" margin:0 10px 0 0 ; padding:5px 0 0 0 ; background: url(toolbar-line.gif) no-repeat right top;"> 99         <a href="#" onClick="doPrint('printPreview');return false;"><img src='print.gif' border=no ></a>100         <a href="<%=appmap%>/servlets/xls?fileName=<%=fileName %>" target="_blank"><img src='excel.gif' border=no ></a>101         <a href="<%=appmap%>/servlets/pdf" target="_blank"><img src='pdf.gif' border=no ></a>102         <a href="<%=appmap%>/servlets/docx?fileName=<%=fileName %>" target="_blank"><img src='doc.gif' border=no ></a>103         </span>104         </td>105       </tr>106    </table>107   </td>108 </table>109 <table width="100%" cellpadding="0" cellspacing="0" border="0">110 <td align="center">111 <%=sbuffer.toString()%>112 </td>113 <script type="text/javascript">114 function doPrint(how)115 {  116   //打印文档对象117   var myDoc ={ 118     documents: document,  // 打印页面(div)们在本文档中119     copyrights :  '杰创软件拥有版权 www.jatools.com'   // 版权声明,必须 120   };121     122   // 调用打印方法123   if(how == 'printPreview')124     jatoolsPrinter.printPreview(myDoc); // 打印预览        125   else if(how == 'printDialog')126     jatoolsPrinter.print(myDoc ,true);  // 打印前弹出打印设置对话框       127   else128     jatoolsPrinter.print(myDoc ,false); // 不弹出对话框打印129 }130 </script>131 132 </table>133 </body>134 </html>

View Code

  5. 报表显示出错页面error.jsp

 1 <%@ page isErrorPage="true" %> 2 <%@ page import="java.io.*" %> 3  4 <html> 5 <head> 6 <title> 7 JasperReports - Web Application Sample 8 </title> 9 <style type="text/css">10 .bnew11 {12   font-decoration:none;13   font-family:'DejaVu Sans', Arial, Helvetica, sans-serif;14   font-size:10pt;15   font-weight:bold;16   color:#990000;17 }18 </style>19 </head>20 21 <body bgcolor="white">22 <span class="bnew">JasperReports encountered this error :</span>23 <pre>24 <% exception.printStackTrace(new PrintWriter(out)); %>25 </pre>26 </body>27 </html>

View Code

  6. 若要支持pdf、img、excel、doc导出,需在web.

 1 <??> 2 <web-app ="http://www.w3.org/2001/  3   ="http://  4   xsi:schemaLocation="http://java.sun.com/  5   version="2.4"> 6  7  <servlet> 8   <servlet-name>PdfServlet</servlet-name> 9   <servlet-class>net.sf.jasperreports.j2ee.servlets.PdfServlet</servlet-class>10  </servlet>11  <servlet>12   <servlet-name>ImageServlet</servlet-name>13   <servlet-class>net.sf.jasperreports.j2ee.servlets.ImageServlet</servlet-class>14  </servlet>15  <servlet>16   <servlet-name>XlsServlet</servlet-name>17   <servlet-class>net.sf.jasperreports.j2ee.servlets.XlsServlet</servlet-class>18  </servlet>19  <servlet>20   <servlet-name>DocxServlet</servlet-name>21   <servlet-class>net.sf.jasperreports.j2ee.servlets.DocxServlet</servlet-class>22  </servlet>23 24  <servlet-mapping>25   <servlet-name>PdfServlet</servlet-name>26   <url-pattern>/servlets/pdf</url-pattern>27  </servlet-mapping>28  <servlet-mapping>29   <servlet-name>ImageServlet</servlet-name>30   <url-pattern>/servlets/image</url-pattern>31  </servlet-mapping>32  <servlet-mapping>33   <servlet-name>XlsServlet</servlet-name>34   <url-pattern>/servlets/xls</url-pattern>35  </servlet-mapping>36  <servlet-mapping>37   <servlet-name>DocxServlet</servlet-name>38   <url-pattern>/servlets/docx</url-pattern>39  </servlet-mapping>40 41 </web-app>

View Code

  7. 在需要显示报表的页面,做如下链接

1 <script src="report.js" language="JavaScript"/>2 <script type="text/javascript">3   function onPrint(){    4     var arg = '{"timeStart":"'+timeStartVal+'","timeEnd":"'+timeEndVal+'"}';5     var param = {jasper:"报表名称",ds:"数据源名称",fileName:"导出的文件名称",args:arg};6     openReport(param);7   }  8 </script>9 <img onclick="onPrint();" image="print.gif" label="打印"/>

View Code

   report.js代码

 1 /*** 2  * 参数说明:{jasper:"report01.jasper",args:arr} 3  * param.jasper:jasper报表名称,最好不要用中文 4  * param.ds:dataSource数据源名称,最好不要用中文 5  * param.args:*格式待定*,暂时用数组,以后看使用什么格式方便可以再改 6 */ 7 function openReport(param){ 8   var strFullPath = window.document.location.href; 9   var strPath = window.document.location.pathname;10   var pos = strFullPath.indexOf(strPath);11   var prePath = strFullPath.substring(0, pos);12   var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);13   var url = postPath;14 15    var blankPageUrl=url+"/report/blank.jsp"16    if(!param.jasper){17      alert("jasper参数为空!");18      return false;19     }20    21   //弹出报表展示窗口,可选择更多的功能,不只是打印,还有导出excel等等22   url+="/report/showReport.jsp?jasper="+param.jasper+"&ds="+param.ds+"&args="+param.args;23   url=encodeURI(url);24   //打开新窗口25   var win=window.open("about:blank");26   win.document.write("报表加载中,请稍候..");27   //创建form对象28   var win_form=win.document.createElement("form");29   win_form.action=url;30   win_form.method="POST";31   win.document.body.appendChild(win_form);32   //参数设置(创建input对象)33   var win_form_input=win.document.createElement("input");34   win_form_input.type="hidden";35   win_form_input.name='fileName';36   win_form_input.value=param.fileName;37   win_form.appendChild(win_form_input);38   //提交表单39   win_form.submit();40 }

View Code