ireport导出文件工具类

package com.ntocc.util.ireport;

import com.ntocc.config.RDSConnection;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Map;

/**
 * @author: luocw
 * @date: 2019/03/04 09:28
 * @Desc: :描述该类的主要功能
 */
@Component
public class IReportUtils {

    private static Connection connection;

    private static Logger logger = LoggerFactory.getLogger(IReportUtils.class);

    /**
     * 获取数据库连接
     * @return
     */
    public static Connection getConnection(){
        String driver = RDSConnection.driver;
        String url = RDSConnection.url;
        String user = RDSConnection.user;
        String pass = RDSConnection.pass;
        try {
            Class.forName(driver);
            Connection con = DriverManager.getConnection(url, user, pass);
            return con;
        }catch(Exception e){
            e. printStackTrace();
            logger.error(e.getMessage());
        }
        return null;
    }

    /**
     * 单例模式
     * @return
     */
    public static Connection getConn(){
        if (connection == null ){
            connection = getConnection();
        }
        return connection;
    }


    /**使用模板和数据库直连模式不安全,不建议使用
     * 导出pdf
     * @param jasperFile
     * @param paramMap
     * @param defaultFileName
     * @param request
     * @param response
     * @throws IOException
     * @throws JRException
     */
    public static void exportToPdf(String jasperFile, Map<String,Object> paramMap, String defaultFileName, HttpServletRequest request,
                                   HttpServletResponse response) throws IOException, JRException {
        if (StringUtils.isEmpty(defaultFileName)){
            defaultFileName =  "export.pdf";
        }else {
            defaultFileName = defaultFileName + ".pdf";
        }
        String fileName = new String(defaultFileName.getBytes("GBK"), "ISO8859_1");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFile,paramMap, getConn());
        ServletOutputStream ouputStream = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }

    /**
     * 导出doc文件
     * @param jasperFile
     * @param paramMap
     * @param defaultFileName
     * @param request
     * @param response
     * @throws IOException
     * @throws JRException
     */
    public static void exportToDoc(String jasperFile, Map<String,Object> paramMap, String defaultFileName, HttpServletRequest request,
                                   HttpServletResponse response) throws IOException, JRException {
        if (StringUtils.isEmpty(defaultFileName)){
            defaultFileName =  "export.doc";
        }else {
            defaultFileName = defaultFileName + ".doc";
        }
        String fileName = new String(defaultFileName.getBytes("GBK"), "ISO8859_1");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFile,paramMap, getConn());
        //设置导出输出流
        JRExporter exporter = new JRRtfExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                response.getOutputStream());
        exporter.exportReport();
    }


    /**
     * 导出html文件
     * @param jasperFile
     * @param paramMap
     * @param request
     * @param response
     * @throws IOException
     * @throws JRException
     */
    public static void exportToHtml(String jasperFile, Map<String,Object> paramMap, HttpServletRequest request,
                                   HttpServletResponse response) throws IOException, JRException {
        response.setContentType("text/html");
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFile,paramMap, getConn());
        ServletOutputStream ouputStream = response.getOutputStream();
        JRHtmlExporter exporter = new JRHtmlExporter();
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
                Boolean.FALSE);
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
        //设置图片文件存放路径,此路径为服务器上的绝对路径
        String imageDIR =request.getSession().getServletContext().getRealPath("/");
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);

        //设置图片请求URI
        String imageURI = request.getContextPath() + "/";
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);

        //设置导出图片到图片存放路径
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
        exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
        exporter.exportReport();

        ouputStream.flush();
        ouputStream.close();
    }


    /**
     * 导出xls文件
     * @param jasperFile
     * @param paramMap
     * @param defaultFileName
     * @param request
     * @param response
     * @throws IOException
     * @throws JRException
     */
    public static void exportToExcel(String jasperFile, Map<String,Object> paramMap, String defaultFileName, HttpServletRequest request,
                                   HttpServletResponse response) throws IOException, JRException {
        if (StringUtils.isEmpty(defaultFileName)){
            defaultFileName =  "export.xls";
        }else {
            defaultFileName = defaultFileName + ".xls";
        }
        String fileName = new String(defaultFileName.getBytes("GBK"), "ISO8859_1");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFile,paramMap, getConn());
        //设置导出输出流
        ServletOutputStream ouputStream = response.getOutputStream();
        JRXlsExporter exporter = new JRXlsExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
        // 删除记录最下面的空行
        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);
        exporter.exportReport();
        ouputStream.flush();
        ouputStream.close();
    }



    /**
     * 导出pdf
     * @param jasperFile
     * @param paramMap
     * @param defaultFileName
     * @param request
     * @param response
     * @throws IOException
     * @throws JRException
     */
    public static void exportToPdf(String jasperFile, Map<String,Object> paramMap, String defaultFileName, HttpServletRequest request,
                                   HttpServletResponse response, JRDataSource dataSource) throws IOException, JRException {
        if (StringUtils.isEmpty(defaultFileName)){
            defaultFileName =  "export.pdf";
        }else {
            defaultFileName = defaultFileName + ".pdf";
        }
        String fileName = new String(defaultFileName.getBytes("GBK"), "ISO8859_1");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        JasperPrint jasperPrint = new JasperPrintWithDataSource(paramMap, jasperFile, dataSource).getJasperPrint();
        ServletOutputStream ouputStream = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }

    /**
     * 导出doc文件
     * @param jasperFile
     * @param paramMap
     * @param defaultFileName
     * @param request
     * @param response
     * @throws IOException
     * @throws JRException
     */
    public static void exportToDoc(String jasperFile, Map<String,Object> paramMap, String defaultFileName, HttpServletRequest request,
                                   HttpServletResponse response, JRDataSource dataSource) throws IOException, JRException {
        if (StringUtils.isEmpty(defaultFileName)){
            defaultFileName =  "export.doc";
        }else {
            defaultFileName = defaultFileName + ".doc";
        }
        String fileName = new String(defaultFileName.getBytes("GBK"), "ISO8859_1");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        JasperPrint jasperPrint = new JasperPrintWithDataSource(paramMap, jasperFile, dataSource).getJasperPrint();

//        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFile,paramMap, getConn());
        //设置导出输出流
        JRExporter exporter = new JRRtfExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                response.getOutputStream());
        exporter.exportReport();
    }


    /**
     * 导出html文件
     * @param jasperFile
     * @param paramMap
     * @param request
     * @param response
     * @throws IOException
     * @throws JRException
     */
    public static void exportToHtml(String jasperFile, Map<String,Object> paramMap, HttpServletRequest request,
                                    HttpServletResponse response, JRDataSource dataSource) throws IOException, JRException {
        response.setContentType("text/html");
        JasperPrint jasperPrint = new JasperPrintWithDataSource(paramMap, jasperFile, dataSource).getJasperPrint();
//        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperFile,paramMap, getConn());
        ServletOutputStream ouputStream = response.getOutputStream();
        JRHtmlExporter exporter = new JRHtmlExporter();
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
                Boolean.FALSE);
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
        //设置图片文件存放路径,此路径为服务器上的绝对路径
        String imageDIR =request.getSession().getServletContext().getRealPath("/");
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR_NAME, imageDIR);

        //设置图片请求URI
        String imageURI = request.getContextPath() + "/";
        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageURI);

        //设置导出图片到图片存放路径
        exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.TRUE);
        exporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
        exporter.exportReport();

        ouputStream.flush();
        ouputStream.close();
    }


    /**
     * 导出xls文件
     * @param jasperFile
     * @param paramMap
     * @param defaultFileName
     * @param request
     * @param response
     * @throws IOException
     * @throws JRException
     */
    public static void exportToExcel(String jasperFile, Map<String,Object> paramMap, String defaultFileName, HttpServletRequest request,
                                     HttpServletResponse response, JRDataSource dataSource) throws IOException, JRException {
        if (StringUtils.isEmpty(defaultFileName)){
            defaultFileName =  "export.xls";
        }else {
            defaultFileName = defaultFileName + ".xls";
        }
        String fileName = new String(defaultFileName.getBytes("GBK"), "ISO8859_1");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        JasperPrint jasperPrint = new JasperPrintWithDataSource(paramMap, jasperFile, dataSource).getJasperPrint();
        //设置导出输出流
        ServletOutputStream ouputStream = response.getOutputStream();
        JRXlsExporter exporter = new JRXlsExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
        // 删除记录最下面的空行
        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);
        exporter.exportReport();
        ouputStream.flush();
        ouputStream.close();
    }

}
package com.ntocc.util.ireport;

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.util.JRLoader;

import java.io.File;
import java.util.Map;

/**
 * 使用报表模板及数据等来生成JapserPrint
 */
public class JasperPrintWithDataSource {

    /** 传入的参数 */
    private Map params;
    /** 模板文件的地址 */
    private String reportFilePath;
    /** dataSrouce */
    private JRDataSource dataSource;
    
    public JasperPrintWithDataSource() {
        super();
    }

    public JasperPrintWithDataSource(Map params, String reportFilePath,JRDataSource dataSource) throws JRRuntimeException {
        if (null == reportFilePath || !reportFilePath.endsWith(".jasper")) 
            throw new JRRuntimeException("您传入的模板文件格式不对,请传入以.jasper为后缀的文件!");
        if (null == dataSource) 
            throw new JRRuntimeException("DataSource不应当为null!");
        this.setReportFilePath(reportFilePath);
        this.setParams(params);
        this.setDataSource(dataSource);
    }

    public Map getParams() {
        return params;
    }

    public void setParams(Map params) {
        this.params = params;
    }

    public JRDataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(JRDataSource dataSource) {
        this.dataSource = dataSource;
    }
    
    public String getReportFilePath() {
        return reportFilePath;
    }

    public void setReportFilePath(String reportFilePath) throws JRRuntimeException {
        if (null == reportFilePath || !reportFilePath.endsWith(".jasper")) 
            throw new JRRuntimeException("您传入的模板文件格式不对,请传入以.jasper为后缀的文件!");
        this.reportFilePath = reportFilePath;
    }
    
    /**  
     * 数据填充,取得JasperPrint  
     * @return  
     * @throws JRRuntimeException  
     */
    public JasperPrint getJasperPrint() throws JRRuntimeException {
        File reportFile = new File(this.reportFilePath); 
        if (!reportFile.exists()) 
            throw new JRRuntimeException("传入的模板文件不存在!");   
        try {
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(reportFile);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, this.params, this.dataSource);
            return jasperPrint;
        } catch (JRException jre) {
            jre.printStackTrace();
            throw new JRRuntimeException("进行数据填充时发生错误!"); 
        }
    }

}
package com.ntocc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author: luocw
 * @date: 2019/03/04 16:16
 * @Desc: :描述该类的主要功能
 */
@Component
public class RDSConnection {

    public static String driver;
    public static String url;
    public static String user;
    public static String pass;

    @Autowired
    public RDSConnection getRDSConnection(@Value("${spring.datasource.driver-class-name}") String driver,
                                          @Value("${spring.datasource.url}") String url,
                                          @Value("${spring.datasource.username}") String user,
                                          @Value("${spring.datasource.password}") String pass) {
        RDSConnection.driver = driver;
        RDSConnection.url = url;
        RDSConnection.user = user;
        RDSConnection.pass = pass;

        return this;
    }

    public static String getDriver() {
        return driver;
    }

    public static void setDriver(String driver) {
        RDSConnection.driver = driver;
    }

    public static String getUrl() {
        return url;
    }

    public static void setUrl(String url) {
        RDSConnection.url = url;
    }

    public static String getUser() {
        return user;
    }

    public static void setUser(String user) {
        RDSConnection.user = user;
    }

    public static String getPass() {
        return pass;
    }

    public static void setPass(String pass) {
        RDSConnection.pass = pass;
    }
}

pom.xml文件添加以下

<!-- jasperreports Start -->
        <!-- 该包的作用完成ireport中Preview按扭功能。通过该包可以通过java来ireport生成摸班(.jrxml或.jasper)填充数据源并导出pdf,excel,html等格式文件 -->
        <dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>6.0.0</version>
        </dependency>
        <dependency>
            <!-- 生成pdf所依赖的包 -->
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.11</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-pdfa</artifactId>
            <version>5.5.11</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>
        <!--将.jrxml编译成.jasper.如果你不使用java编译,而使用ireport工具编译则无须导入该 包  -->
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.13</version>
        </dependency>
        <!--导入excel文件需要的包,最起码下载3.9版本-->
        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/itext/itext -->
        <dependency>
            <groupId>itext</groupId>
            <artifactId>itext</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!-- jasperreports End -->

 

posted @ 2019-03-04 17:08  进击小螺号  阅读(660)  评论(2)    收藏  举报