首页 > 编程语言 >Jasper ReportUtils

Jasper ReportUtils

时间:2023-09-14 12:07:32浏览次数:65  
标签:exporter ReportUtils param throws Jasper import net response


import java.io.File;
import java.io.IOException;   
import java.io.OutputStream;   
import java.io.PrintWriter;   
import java.net.URLEncoder;   
import java.util.List;   
import java.util.Map;   

import javax.servlet.ServletException;   
import javax.servlet.http.HttpServletRequest;   
import javax.servlet.http.HttpServletResponse;   
import javax.servlet.http.HttpSession;   

import net.sf.jasperreports.engine.JRAbstractExporter;   
import net.sf.jasperreports.engine.JRDataSource;   
import net.sf.jasperreports.engine.JRException;   
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.data.JRBeanCollectionDataSource;   
import net.sf.jasperreports.engine.export.JExcelApiExporter;   
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.JRRtfExporter;   
import net.sf.jasperreports.engine.export.JRXmlExporter;   
import net.sf.jasperreports.engine.util.JRLoader;   
import net.sf.jasperreports.j2ee.servlets.ImageServlet;   

/**  
 * 使用jasperReport做报表时的工具支持类.有两个用途,生成jasperPrint对象,和设置导出时的session  
 */  
public class ReportUtils {   
    private HttpServletRequest request;   
    private HttpServletResponse response;   
//    private HttpSession session;   

    /**  
     * 在其它web环境下构造此工具类对象  
     *   
     * @param request  
     *            request请求对象  
     */  
    public ReportUtils(HttpServletRequest request) {   
        this.request = request;   
//        this.session = request.getSession();   
    }   

    public ReportUtils(HttpServletResponse response) {   
        this.response = response;   
    }   

    public ReportUtils(HttpServletRequest request, HttpServletResponse response) {   
        this(request);   
        this.response = response;   
    }   

    /**  
     * 获得JasperPrint对象;自定义填充报表时的parameter和dataSource. 参数说明和动态表头的用法参考上一方法  
     *   
     * @param filePath  
     * @param parameter  
     * @param dataSource  
     * @param sizeGroup  
     * @return  
     */  
    public JasperPrint getJasperPrint(String filePath, Map parameter,   
            JRDataSource dataSource) throws JRException {   
        JasperReport jasperReport = null;   
        try {   
            jasperReport = (JasperReport) JRLoader.loadObject(new File(filePath));   
            return JasperFillManager.fillReport(jasperReport, parameter,   
                    dataSource);   
        } catch (JRException e) {   
            e.printStackTrace();   
        }   
        return null;   
    }   

    /**  
     * 通过传入List类型数据源获取JasperPrint实例  
     *   
     * @param filePath  
     *            jasper路径  
     * @param parameter  
     * @param list  
     * @return  
     * @throws JRException  
     */  
    public JasperPrint getPrintWithBeanList(String filePath, Map parameter,   
            List list) throws JRException {   
        JRDataSource dataSource = new JRBeanCollectionDataSource(list);   
        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;   
        }   
        return exporter;   
    }   

//    public void setAttrToPage(JasperPrint jasperPrint, String report_fileName,   
//            String report_type) {
//        request.setAttribute("REPORT_JASPERPRINT", jasperPrint);   
//        request.setAttribute("REPORT_FILENAME", report_fileName);   
//        request.setAttribute("REPORT_TYPE", report_type);   
//    }   

    /**  
     * 定义了报表输出类型,固定了可输出类型  
     *   
     * @author Administrator  
     *   
     */  
    public static enum DocType {   
        PDF, HTML, XLS, XML, RTF   
    }   

    /**  
     * 编译报表模板文件jaxml,生成jasper二进制文件  
     *   
     * @param jaxmlPath  
     * @param jasperPath  
     * @throws JRException  
     */  
    public void complieJaxml(String jaxmlPath, String jasperPath)   
            throws JRException {   
        JasperCompileManager.compileReportToFile(jaxmlPath, jasperPath);   
    }   

    /**  
     * 输出PDF 使用此方法,必须预先注入response  
     *   
     * @param jasperPath  
     * @param params  
     * @param sourceList  
     * @param fileName  
     * @throws JRException  
     * @throws IOException  
     * @throws ServletException  
     */  
    public void servletExportPDF(String jasperPath, Map params,   
            List sourceList, String fileName) throws JRException, IOException,   
            ServletException {   
        servletExportDocument(DocType.PDF, jasperPath, params, sourceList,   
                fileName);   
    }   

    /**  
     * 输出html静态页面,必须注入request和response  
     *   
     * @param jasperPath  
     * @param params  
     * @param sourceList  
     * @param imageUrl  
     *            报表文件使用的图片路径,比如 ../servlets/image?image=  
     * @throws JRException  
     * @throws IOException  
     * @throws ServletException  
     */  
    public void servletExportHTML(String jasperPath, Map params,   
            List sourceList, String imageUrl) throws JRException, IOException,   
            ServletException {   
        response.setContentType("text/html");   
        response.setCharacterEncoding("UTF-8");   
        JRAbstractExporter exporter = getJRExporter(DocType.HTML);   

        JasperPrint jasperPrint = getPrintWithBeanList(jasperPath, params,   
                sourceList);   

        request.setAttribute(   
                ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,   
                jasperPrint);   

        PrintWriter out = response.getWriter();   

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);   
        exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, out);   
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl);   
        exporter.exportReport();   
    }   

    /**  
     * 输出Excel报表文件  
     *   
     * @param jasperPath  
     * @param params  
     * @param sourceList  
     * @param fileName  
     * @throws JRException  
     * @throws IOException  
     * @throws ServletException  
     */  
    public void servletExportExcel(String jasperPath, Map params,   
            List sourceList, String fileName) throws JRException, IOException,   
            ServletException {   
        servletExportDocument(DocType.XLS, jasperPath, params, sourceList,   
                fileName);   
        // 要想获得更好的视觉效果,可以添加以下代码   
        // // exporter.setParameter(   
        // // JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,   
        // // Boolean.TRUE); // 删除记录最下面的空行   
        // //   
        // exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,   
        // // Boolean.FALSE);// 删除多余的ColumnHeader   
        // //   
        // exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND   
        // ,   
        // // Boolean.FALSE);// 显示边框   
    }   

    /**  
     * 生成不同格式报表文档  
     *   
     * @param docType  
     *            文档类型  
     * @param jasperPath  
     * @param params  
     * @param sourceList  
     * @param fileName  
     * @throws JRException  
     * @throws IOException  
     * @throws ServletException  
     */  
    public void servletExportDocument(DocType docType, String jasperPath,   
            Map params, List sourceList, String fileName) throws JRException,   
            IOException, ServletException {   

        if (docType == DocType.HTML) {   
            servletExportHTML(jasperPath, params, sourceList, fileName);   
            return;   
        }   

        JRAbstractExporter exporter = getJRExporter(docType);   
        // 获取后缀   
        String ext = docType.toString().toLowerCase();   

        if (!fileName.toLowerCase().endsWith(ext)) {   
            fileName += "." + ext;   
        }   
        // 判断资源类型   
        String contentType = "application/";   
        if (ext.equals("xls")) {   
            ext = "excel";   
        } else if (ext.equals("xml")) {   
            contentType = "text/";   
        }   
        contentType += ext;   

        response.setContentType(contentType);   
        response.setHeader("Content-Disposition", "attachment; filename=\""  
                + URLEncoder.encode(fileName, "UTF-8") + "\"");   

        exporter.setParameter(JRExporterParameter.JASPER_PRINT,   
                getPrintWithBeanList(jasperPath, params, sourceList));   

        OutputStream ouputStream = response.getOutputStream();   

        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);   
        try {   
            exporter.exportReport();   
        } catch (JRException e) {   
            throw new ServletException(e);   
        } finally {   
            if (ouputStream != null) {   
                try {   
                    ouputStream.close();   
                } catch (IOException ex) {   
                }   
            }   
        }   
    }   
}




一、导出报表到html



InputStream inputStream = ServletActionContext.getServletContext().getResourceAsStream("/report/xxx.jasper");  
    Collection<xxxo> data=xxxService.getData(params);  
    Map<Object,Object> map=xxxService.getMap(startTime, endTime);  

    JRBeanCollectionDataSource dataSource=new JRBeanCollectionDataSource(data);  
    //填充报表  
    JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream,map, dataSource);  
    //设置输出类型及报表的内置参数  
    response.setContentType("text/html");  
    OutputStream outputStream=response.getOutputStream();  
    ReportXHtmlExporter htmlExporter=new ReportXHtmlExporter(page,jasperPrint);  
    request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,jasperPrint);  
    htmlExporter.setParameter(JRExporterParameter.JASPER_PRINT,jasperPrint);  
    htmlExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);  
    if(jasperPrint.getPages().size()>1){  
        htmlExporter.setParameter(JRExporterParameter.PAGE_INDEX, 1);  
    }  
    htmlExporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,Boolean.FALSE);  
    htmlExporter.exportReport();  
    outputStream.flush();  
    outputStream.close();




二、导出到PDF



OutputStream outputStream=response.getOutputStream();  
    File reportFile = new File(ServletActionContext.getServletContext().getRealPath("/report/xxx.jasper"));  
    if (!reportFile.exists()){  
        throw new JRRuntimeException("File dispatch_report.jasper not found.");  
    }  
    JasperReport jasperReport = (JasperReport)JRLoader.loadObject(reportFile.getPath());  

    //javabean数据源  
    Collection<xxx> data=xxxService.getData(params);  
    Map<Object,Object> map=xxxService.getMap(startTime, endTime);  
    JRBeanCollectionDataSource dataSource=new JRBeanCollectionDataSource(data);  
    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,map, dataSource);  

    JRPdfExporter pdfExporter=new JRPdfExporter();  
    pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);  
    pdfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);   
    response.setContentType("application/pdf");  
    response.setCharacterEncoding("UTF-8");    
    response.setHeader("Content-Disposition", "attachment; filename=\""  + URLEncoder.encode("XXX报表", "UTF-8") + ".pdf\"");   
    pdfExporter.exportReport();  
    outputStream.flush();  
    outputStream.close();




三、web.xml配置


<!--JasperReport显示图片的,象素图片-->  
        <servlet>  
            <servlet-name>ImageServlet</servlet-name>  
            <servlet-class>net.sf.jasperreports.j2ee.servlets.ImageServlet</servlet-class>  
        </servlet>  
        <servlet-mapping>  
            <servlet-name>ImageServlet</servlet-name>  
            <!-- /report/image路径,report表示struts中的表空间(具体就看url请求的路径),image表示Action文件里配置image?image=问号前的image相同-->  
            <url-pattern>/report/image</url-pattern>  
        </servlet-mapping>

标签:exporter,ReportUtils,param,throws,Jasper,import,net,response
From: https://blog.51cto.com/u_16261339/7468591

相关文章

  • JasperReports+iReport在eclipse中的使用
    一、介绍1)它可以PDF,HTML,XML等多种形式产生报表或动态报表,在新版本还支持CSV,XLS,RTF等格式的报表;2)它按预定义的XML文档来组织数据,来源多(如:关系数据库,Java容器对象(collection,arrays)等);报表的填充过程:先产生报表设计对象->序列化该对象->存储在磁盘或网络-......
  • org.apache.jasper.servlet.TldScanner$TldScannerCallback.scan(Lorg/apache/tomcat/
    原因<dependency><groupId>org.apache.hive</groupId><artifactId>hive-jdbc</artifactId><version>3.1.3</version></dependency>解决<dependency>......
  • jasper简单使用
    下载古老的IReport报表编辑器。链接:https://community.jaspersoft.com/project/ireport-designer/releases,最后打包时间为2014年5月,最终版本停留在v5.6.0。由于IReport最高支持jdk7,所以一般会启动失败,推荐下载7u80,便可顺利启动:编辑配置文件:【D:\iReport-4.5.1\etc下的irepor......
  • 上传jrxml模板进行JasperReport解析导致任意代码执行RCE
    JasperReport是一个强大、灵活的报表生成工具,能够展示丰富的页面内容,并将之转换成PDF、HTML、XML等格式。该库完全由Java写成,可以用于在各种Java应用程序,包括J2EE,Web应用程序中生成动态内容。JasperReports附带了报表编译器,可以在报表表达式内部使用Groovy脚本语言或JavaScript编......
  • 在Web里面用Jasper导出Pdf、HTML、Excel,以及参数说明
    参考:[color=red]ireport导出各种格式(pdf,excel,word,html,print)的例子[/color]:[url]http://mingxiao2010.blog.163.com/blog/static/861904812010665366872/[/url]说明:PDF:JRAbstractExporterexporter=newJRPdfExporter();Excel:JRAbstractExpor......
  • 从iReport到Jaspersoft Studio
    从5.5版本开始,JaspersoftStudio将取代iReport成为JasperReports官方设计器。iReport维护截止日期到2015年底,意味着不会再有新的功能增加进iReport,但会做一些关键bug的修复、更新。所幸的是基于eclipse的JaspersoftStudio同样开源、免费!Yeah!JaspersoftStudio是一个专为Jasper......
  • 由“Jasperrpeorts 4.1.2升级到5.1.2对flex项目的解析”到AS3 带命名空间的XML的操作
    项目中,对Jasperrpeorts-4.1.2核心包进行了升级,发现,前端flex无法对Jasperrpeorts的格式进行解析了~iReport4.1设计的模版可以解析,而iReport4.6设计的模版就不行了~断点后,对比了从后台传过来的Jasperrpeorts的xml数据,发现存在差异 4.1.2包生成的xml数据jasperPrint标签......
  • 从iReport到Jaspersoft Studio
    从5.5版本开始,JaspersoftStudio将取代iReport成为JasperReports官方设计器。iReport维护截止日期到2015年底,意味着不会再有新的功能增加进iReport,但会做一些关键bug的修复、更新。所幸的是基于eclipse的JaspersoftStudio同样开源、免费!Yeah!JaspersoftStudio是一个专为Jasper......
  • JasperReport报表导出PDF中文不显示的问题
       首先在JasperReportStudio中加载下载好的中文字体:打开设置页面:Window>>Preferences>>JaspersoftStudio>>Fonts,点击Add添加字体,FamilyName中命名新添加字体名称,TrueType中选择下载的字体文件(.ttf文件),PDFEncoding中选择PDF中中文字体编码格式。     这......
  • org.apache.jasper.JasperException: Unable to compile class for JSP: An error occ
    org.apache.jasper.JasperException:UnabletocompileclassforJSP:Anerroroccurredatline:16inthejspfile:/monday-01.jspSystem.outcannotberesolvedtoatype13:<body>14:<%15:Stringa=request.getParameter("uname");......