iReport与JasperReport简介(二)
1.iReport 报表工具类
package com.runan.util.iReport; /** * iReport 报表工具 */ public class IreportUtils { /** * 获得JasperPrint对象;自定义填充报表时的parameter和dataSource. * @param filePath 模板路径 * @param parameter 参数 * @param dataSource 数据源(list,object[],map) */ public JasperPrint getJasperPrint(String filePath, Map parameter, JRDataSource dataSource) throws JRException { JasperReport jasperReport = null; try { //jasperReport = (JasperReport) JRLoader.loadObject(filePath); jasperReport = (JasperReport) JRLoader.loadObjectFromFile(filePath); return JasperFillManager.fillReport(jasperReport, parameter, dataSource); } catch (JRException e) { e.printStackTrace(); } return null; } /** * 获得JasperPrint对象;自定义填充报表时的parameter和connection * @param filePath 模板路径 * @param parameter 参数 * @param conn 数据库连接 */ public JasperPrint getJasperPrint(String filePath, Map parameter, Connection conn) throws JRException { JasperReport jasperReport = null; try { //jasperReport = (JasperReport) JRLoader.loadObject(filePath); jasperReport = (JasperReport) JRLoader.loadObjectFromFile(filePath); return JasperFillManager.fillReport(jasperReport, parameter, conn); } catch (JRException e) { e.printStackTrace(); } return null; } /** * 通过传入List类型数据源获取JasperPrint实例 * @param filePath 模板路径 * @param parameter 参数 * @param list 数据源 */ public JasperPrint getPrintWithBeanList(String filePath, Map parameter, List list) throws JRException { JRDataSource dataSource = new JRBeanCollectionDataSource(list); return getJasperPrint(filePath, parameter, dataSource); } /** * 通过传入List类型数据源获取JasperPrint实例 * @param filePath 模板路径 * @param parameter 参数 * @param Objcet[] 数据源 */ public JasperPrint getPrintWithBeanArayy(String filePath, Map parameter, Object[] objArray) throws JRException { JRDataSource dataSource = new JRBeanArrayDataSource(objArray); return getJasperPrint(filePath, parameter, dataSource); } /** * 传入类型,获取输出器 * * @param docType * @return */ public JRAbstractExporter getJRExporter(DocType docType) { JRAbstractExporter exporter = null; switch (docType) { case PDF: exporter = new JRPdfExporter(); break; case HTML: exporter = new JRHtmlExporter(); break; case XLS: exporter = new JExcelApiExporter(); break; case XML: exporter = new JRXmlExporter(); break; case RTF: exporter = new JRRtfExporter(); break; case CSV: exporter = new JRCsvExporter(); break; case TXT: exporter = new JRTextExporter(); break; case DOC: exporter = new JRRtfExporter(); break; } return exporter; } /** * 获得相应类型的Content type * @param docType * @return */ public String getContentType(DocType docType){ String contentType="text/html"; switch(docType){ case PDF: contentType = "application/pdf"; break; case XLS: contentType = "application/vnd.ms-excel"; break; case XML: contentType = "text/xml"; break; case RTF: contentType = "application/rtf"; break; case CSV: contentType = "text/plain"; break; case DOC: contentType = "application/msword;charset=utf-8"; break; } return contentType; } /** * 编译报表模板文件jrxml,生成jasper二进制文件 * @param jrxmlPath 报表设计文件 * @param jrsperPath 报表编译后文件 * @throws JRException */ public void complieJrxml(String jrxmlPath, String jasperPath) throws JRException { JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath); } /** * 定义了报表输出类型,固定了可输出类型 */ public static enum DocType { PDF, HTML, XLS, XML, RTF, CSV, TXT, DOC } /** * 输出html静态页面,必须注入request和response * @param jasperPath * @param params * @param sourceList * @param imageUrl * 报表文件使用的图片路径,比如 ../image?image= * @param response * @throws Exception */ public void servletExportHTMLList(String jasperPath, Map params, List sourceList, String imageUrl,HttpServletResponse response) throws Exception{ response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); JRAbstractExporter exporter = getJRExporter(DocType.HTML); JasperPrint jasperPrint = getPrintWithBeanList(jasperPath, params, sourceList); PrintWriter out = response.getWriter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out); exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl); exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,false);//不显示px exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.FALSE); exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "
"); exporter.exportReport(); } /** * 输出html静态页面,必须注入request和response * @param jasperPath * @param params * @param sourceList * @param imageUrl * 报表文件使用的图片路径,比如 ../image?image= * @param response * @throws Exception */ public void servletExportHTMLArray(String jasperPath, Map params, Object[] sourceArray, String imageUrl,HttpServletResponse response) throws Exception{ response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); JRAbstractExporter exporter = getJRExporter(DocType.HTML); JasperPrint jasperPrint = getPrintWithBeanArayy(jasperPath, params, sourceArray); PrintWriter out = response.getWriter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out); exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl); exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,false);//不显示px exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.FALSE); exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "
"); exporter.exportReport(); } /** * 输出html静态页面,必须注入request和response * @param jasperPath * @param params * @param sourceList * @param imageUrl * 报表文件使用的图片路径,比如 ../image?image= * @param response * @throws Exception */ public void servletExportHTML(String jasperPath, Map params, Connection con, String imageUrl, HttpServletResponse response) throws Exception{ response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); JRAbstractExporter exporter = getJRExporter(DocType.HTML); JasperPrint jasperPrint = getJasperPrint(jasperPath, params, con); PrintWriter out = response.getWriter(); exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out); exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl); exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,false);//不显示px exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.FALSE); exporter.setParameter(JRHtmlExporterParameter.BETWEEN_PAGES_HTML, "
"); exporter.exportReport(); } /** * 生成不同格式报表文档 * @param docType 文档类型 * @param jasperPath * @param params * @param sourceList * @param fileName * @param response */ public void exportDocumentList(DocType docType, String jasperPath, Map params, List sourceList, String fileName, HttpServletResponse response) throws Exception{ if (docType == DocType.HTML) { servletExportHTMLList(jasperPath, params, sourceList, fileName, response); return; } JRAbstractExporter exporter = getJRExporter(docType); // 获取后缀 String ext = docType.toString().toLowerCase(); if (!fileName.toLowerCase().endsWith(ext)) { fileName += "." + ext; } // 判断资源类型 if (ext.equals("xls")) { // 删除记录最下面的空行 exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); // 删除多余的ColumnHeader exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE); // 显示边框 exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); } response.setContentType(getContentType(docType)); response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\""); exporter.setParameter(JRExporterParameter.JASPER_PRINT, getPrintWithBeanList(jasperPath, params, sourceList)); OutputStream outStream = null; PrintWriter outWriter = null; if(ext.equals("csv")){//解决中文乱码问题 response.setCharacterEncoding("GBK"); outWriter = response.getWriter(); exporter.setParameter(JRExporterParameter.OUTPUT_WRITER,outWriter); }else{ outStream = response.getOutputStream(); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outStream); if(ext.equals("txt")){ exporter.setParameter(JRTextExporterParameter.CHARACTER_WIDTH, new Integer(80)); exporter.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT, new Integer(25)); exporter.setParameter(JRTextExporterParameter.CHARACTER_ENCODING,"GBK"); } } try { exporter.exportReport(); } catch (JRException e) { throw new Exception(e); } finally { if (outStream != null) { try { outStream.close(); } catch (IOException ex) { } } } } /** * 生成不同格式报表文档 * @param docType 文档类型 * @param jasperPath * @param params * @param sourceList * @param fileName * @param response */ public void exportDocumentArray(DocType docType, String jasperPath, Map params, Object[] sourceArray, String fileName, HttpServletResponse response) throws Exception{ if (docType == DocType.HTML) { servletExportHTMLArray(jasperPath, params, sourceArray, fileName, response); return; } JRAbstractExporter exporter = getJRExporter(docType); // 获取后缀 String ext = docType.toString().toLowerCase(); if (!fileName.toLowerCase().endsWith(ext)) { fileName += "." + ext; } // 判断资源类型 if (ext.equals("xls")) { // 删除记录最下面的空行 exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); // 删除多余的ColumnHeader exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE); // 显示边框 exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); } response.setContentType(getContentType(docType)); response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\""); exporter.setParameter(JRExporterParameter.JASPER_PRINT, getPrintWithBeanArayy(jasperPath, params, sourceArray)); OutputStream outStream = null; PrintWriter outWriter = null; if(ext.equals("csv")){//解决中文乱码问题 response.setCharacterEncoding("GBK"); outWriter = response.getWriter(); exporter.setParameter(JRExporterParameter.OUTPUT_WRITER,outWriter); }else{ outStream = response.getOutputStream(); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outStream); if(ext.equals("txt")){ exporter.setParameter(JRTextExporterParameter.CHARACTER_WIDTH, new Integer(80)); exporter.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT, new Integer(25)); exporter.setParameter(JRTextExporterParameter.CHARACTER_ENCODING,"GBK"); } } try { exporter.exportReport(); } catch (JRException e) { throw new Exception(e); } finally { if (outStream != null) { try { outStream.close(); } catch (IOException ex) { } } } } /** * 生成不同格式报表文档 * @param docType 文档类型 * @param jasperPath 模板文件路径 * @param params 参数 * @param con 连接 * @param fileName 输出文件名 * @param response 相应对象 */ //public void exportDocumentCon(DocType docType, String jasperPath, Map params, Connection con, String fileName, HttpServletResponse response) throws Exception{ public void exportDocumentCon(DocType docType, String jasperPath, Map params, String fileName, HttpServletResponse response) throws Exception{ DataSource dataSource ; WebApplicationContext cont = WebApplicationContextUtils .getRequiredWebApplicationContext(RequestFilter.threadLocalRequest.get() .getSession().getServletContext()); dataSource = (DataSource)cont.getBean("dataSource"); Connection con = dataSource.getConnection(); if (docType == DocType.HTML) { servletExportHTML(jasperPath, params, con, fileName, response); return; } JRAbstractExporter exporter = getJRExporter(docType); // 获取后缀 String ext = docType.toString().toLowerCase(); if (!fileName.toLowerCase().endsWith(ext)) { fileName += "." + ext; } // 判断资源类型 if (ext.equals("xls")) { // 删除记录最下面的空行 exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); // 删除多余的ColumnHeader exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE); // 显示边框 exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE); } response.setContentType(getContentType(docType)); response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\""); exporter.setParameter(JRExporterParameter.JASPER_PRINT, getJasperPrint(jasperPath, params, con)); OutputStream outStream = null; PrintWriter outWriter = null; if(ext.equals("csv")){ //解决中文乱码问题 response.setCharacterEncoding("GBK"); outWriter = response.getWriter(); exporter.setParameter(JRExporterParameter.OUTPUT_WRITER,outWriter); }else{ outStream = response.getOutputStream(); exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outStream); if(ext.equals("txt")){ exporter.setParameter(JRTextExporterParameter.CHARACTER_WIDTH, new Integer(80)); exporter.setParameter(JRTextExporterParameter.CHARACTER_HEIGHT, new Integer(25)); exporter.setParameter(JRTextExporterParameter.CHARACTER_ENCODING,"GBK"); } } try { exporter.exportReport(); } catch (JRException e) { throw new Exception(e); } finally { if (outStream != null) { try { outStream.flush(); outStream.close(); } catch (IOException ex) { ex.printStackTrace(); } } } } public static DocType getEnumDocType(String docType){ DocType type = DocType.HTML; docType = docType.toUpperCase(); if(docType.equals("PDF")){ type = DocType.PDF; }else if(docType.equals("XLS")){ type = DocType.XLS; }else if(docType.equals("XML")){ type = DocType.XML; }else if(docType.equals("RTF")){ type = DocType.RTF; }else if(docType.equals("CSV")){ type = DocType.CSV; }else if(docType.equals("TXT")){ type = DocType.TXT; }else if(docType.equals("DOC")){ type = DocType.DOC; } return type; } /** * 预览不同格式报表文档 * @param docType 文档类型 * @param jasperPath * @param params * @param sourceList */ public void viewDocumentArray(String jasperPath, Map params, Object[] sourceArray) throws Exception{ try { JasperViewer.viewReport(getPrintWithBeanArayy(jasperPath, params, sourceArray)); } catch (JRException e) { throw new Exception(e); } finally { } } /** * 预览不同格式报表文档 * @param docType 文档类型 * @param jasperPath * @param params * @param sourceList */ public void viewDocumentList(String jasperPath, Map params, List sourceArray) throws Exception{ try { JasperViewer.viewReport(getPrintWithBeanList(jasperPath, params, sourceArray)); } catch (JRException e) { throw new Exception(e); } finally { } } }
2.Controller类
@RequestMapping(params = "report") public void report(String ddlx,HttpServletRequest request,HttpServletResponse response){ String idsArray[] = request.getParameterValues("id"); Transferwithin transferwithin = transferwithinService.getTransferwithinById(idsArray[0]); CommonConfig config = new CommonConfig(); config.setCode(transferwithin.getDdhszjq()); config.setGroupCode("JQ"); config = commonConfigService.getCommonConfigbyCode(config); IreportUtils ireportUtils = new IreportUtils(); String jasperPath="/report/ireportTemplete/zf_djtzs.jasper"; jasperPath = request.getSession().getServletContext().getRealPath(jasperPath); String fileName="罪犯调监通知书"; Mapparams= new HashMap (); try { params.put("title", "罪犯调动通知单 (存根)"); params.put("zihao", transferwithin.getDlxh()); params.put("content", " 因为改造需要,经研究同意将罪犯 "+transferwithin.getXm()+"等"+idsArray.length+"名分给"+config.getName()+",请于"+DateUtils.dateToString(transferwithin.getDdrq(), "yyyy年MM月dd日")+"前办理好交接手续。"); params.put("fmd", "附名单:"+transferwithinService.getZfXmString(idsArray)); params.put("name", "德州监狱狱政管理科"); params.put("makedate", DateUtils.dateToString(new Date(), "yyyy年MM月dd日")); ireportUtils.exportDocumentCon(DocType.PDF, jasperPath, params,fileName, response); } catch (Exception e) { throw new RunanException(e.getMessage()); } }
导出图见附件,当然PDF某些元素是靠iReport工具生成。