Java中使用ireport导出excel

pom.xml文件中添加如下配置引入jar包
我这里jasperreports用的是5.6版本 spring版本是4.3.9

        
        	net.sf.jasperreports
        	jasperreports
        	5.6.0
        
        
        	com.lowagie
        	itext
        	2.1.7
        
        
        	org.olap4j
        	olap4j
        	1.2.0
        
        
        	xml-apis
        	xml-apis
        	1.4.01
        
        
        	org.codehaus.groovy
        	groovy-all
        	2.4.13
        
        

     com.fasterxml.jackson.core
     jackson-core
     2.8.8
   
  
  com.fasterxml.jackson.core
  jackson-databind
  2.8.8
  
  
    com.fasterxml.jackson.core
    jackson-annotations
    2.8.8
  

Java中使用ireport导出excel_第1张图片
数据源有两种方式 一种是直接连接数据库 还有一种是使用JavaBean
这里只介绍JavaBean的方式

Java中使用ireport导出excel_第2张图片
在这里可以右键字段 要与JavaBean的字段对应上 不然取不到值
Java中使用ireport导出excel_第3张图片
这里可以定义函数 用来计算合计等
Java中使用ireport导出excel_第4张图片
Java中使用ireport导出excel_第5张图片
页面结构 title是标题 这里放了一个静态文本框
Java中使用ireport导出excel_第6张图片
page header是页面头部 这里是取的后台传过来的数据
$P{REPORT_PARAMETERS_MAP}.get( “date” ) date是参数的名称

column header表头 静态文本框

details 详细页 会循环多次 用的text field
Java中使用ireport导出excel_第7张图片选择text field右键选edit expression
Java中使用ireport导出excel_第8张图片
双击fields取值
Java中使用ireport导出excel_第9张图片
preview预览 之后会生成所需要的文件 .jasper结尾

后台代码

		//这里是要导出的数据
		List statisticalSalesByCustomer = 		statisticalInfoMapper.toStatisticalSalesByCustomer(starttime, endtime, null, keyword);
		
		//JRBeanCollectionDataSource通过构造注入collection类型的参数,这里我们用的是list结构  
        JRDataSource jrDataSource = new JRBeanCollectionDataSource(statisticalSalesByCustomer);
        
        // 设定报表所需要的外部参数内容 参数名date
     	Map rptParameters = new HashMap();
     	rptParameters.put("date", "日期:"+starttime+"-"+endtime);
     	//指定模板文件 刚才生成的文件
        ServletContext context = request.getSession().getServletContext();
        File reportFile = null;
        reportFile = new File(context.getRealPath("/WEB-INF/page/statistical/StatisticalSalesByCustomer.jasper"));
        //指定导出文件名称
        String exportFilePath = "销售统计";
        //导出
        JasperHelper.export("excel", exportFilePath, reportFile, request, response, rptParameters, jrDataSource); 

用到的工具类

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRAbstractExporter;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.base.JRBaseReport;
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.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.export.JRXmlExporter;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;

import org.apache.log4j.Logger;

import java.sql.Connection;

@SuppressWarnings("deprecation")
public class JasperHelper {
    private static Logger logger = Logger.getLogger(JasperHelper.class);
    public static final String PRINT_TYPE = "print";
    public static final String PDF_TYPE = "pdf";
    public static final String EXCEL_TYPE = "excel";
    public static final String HTML_TYPE = "html";
    public static final String WORD_TYPE = "word";

    public static void prepareReport(JasperReport jasperReport, String type) {
        logger.debug("The method======= prepareReport() start.......................");
        /*
         * 如果导出的是excel,则需要去掉周围的margin
         */
        if ("excel".equals(type))
            try {
                Field margin = JRBaseReport.class
                        .getDeclaredField("leftMargin");
                margin.setAccessible(true);
                margin.setInt(jasperReport, 0);
                margin = JRBaseReport.class.getDeclaredField("topMargin");
                margin.setAccessible(true);
                margin.setInt(jasperReport, 0);
                margin = JRBaseReport.class.getDeclaredField("bottomMargin");
                margin.setAccessible(true);
                margin.setInt(jasperReport, 0);
                Field pageHeight = JRBaseReport.class
                        .getDeclaredField("pageHeight");
                pageHeight.setAccessible(true);
                pageHeight.setInt(jasperReport, 2147483647);
            } catch (Exception exception) {
            }
    }

    /**
     * 导出excel
     */
    public static void exportExcel(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response) throws IOException, JRException {
        /*
         * 设置头信息
         */
        response.setContentType("application/vnd.ms-excel");
        String defaultname = null;
        if (defaultFilename.trim() != null && defaultFilename != null) {
            defaultname = defaultFilename + ".xls";
        } else {
            defaultname = "export.xls";
        }

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


        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); // 删除记录最下面的空行

        exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
                Boolean.FALSE);// 删除多余的ColumnHeader
        //
        exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,
                Boolean.FALSE);// 显示边框
        exporter.exportReport();
        ouputStream.flush();
        ouputStream.close();
    }

    public static enum DocType {
        PDF, HTML, XLS, XML, RTF
    }
    @SuppressWarnings("rawtypes")
    public static 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;
    }
    /**
     * 导出pdf,注意此处中文问题,
     * 
     * 这里应该详细说:主要在ireport里变下就行了。看图
     * 
     * 1)在ireport的classpath中加入iTextAsian.jar 2)在ireport画jrxml时,看ireport最左边有个属性栏。
     * 
     * 下边的设置就在点字段的属性后出现。 pdf font name :STSong-Light ,pdf encoding :UniGB-UCS2-H
     */
    private static void exportPdf(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response) throws IOException, JRException {
        response.setContentType("application/pdf");
        String defaultname = null;
        if (defaultFilename.trim() != null && defaultFilename != null) {
            defaultname = defaultFilename + ".pdf";
        } else {
            defaultname = "export.pdf";
        }
        String fileName = new String(defaultname.getBytes("GBK"), "ISO8859_1");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        ServletOutputStream ouputStream = response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }

    /**
     * 导出html
     */
    private static void exportHtml(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response) throws IOException, JRException {
        response.setContentType("text/html");
        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();
    }

    /**
     * 导出word
     */
    @SuppressWarnings("rawtypes")
    private static void exportWord(JasperPrint jasperPrint,
            String defaultFilename, HttpServletRequest request,
            HttpServletResponse response) throws JRException, IOException {
        response.setContentType("application/msword;charset=utf-8");
        String defaultname = null;
        if (defaultFilename.trim() != null && defaultFilename != null) {
            defaultname = defaultFilename + ".doc";
        } else {
            defaultname = "export.doc";
        }
        String fileName = new String(defaultname.getBytes("GBK"), "utf-8");
        response.setHeader("Content-disposition", "attachment; filename="
                + fileName);
        JRExporter exporter = new JRRtfExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                response.getOutputStream());

        exporter.exportReport();
    }

    /**
     * 按照类型导出不同格式文件
     * 
     * @param datas
     *            数据
     * @param type
     *            文件类型
     * @param is
     *            jasper文件的来源
     * @param request
     * @param response
     * @param defaultFilename默认的导出文件的名称
     */
    public static void export(String type, String defaultFilename, File is,
            HttpServletRequest request, HttpServletResponse response,
            Map parameters, Connection conn) {
        try {
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
            prepareReport(jasperReport, type);

            JasperPrint jasperPrint = JasperFillManager.fillReport(
                    jasperReport, parameters, conn);

            if (EXCEL_TYPE.equals(type)) {
                exportExcel(jasperPrint, defaultFilename, request, response);
            } else if (PDF_TYPE.equals(type)) {
                exportPdf(jasperPrint, defaultFilename, request, response);
            } else if (HTML_TYPE.equals(type)) {
                exportHtml(jasperPrint, defaultFilename, request, response);
            } else if (WORD_TYPE.equals(type)) {
                exportWord(jasperPrint, defaultFilename, request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void export(String type, String defaultFilename, File is,
            HttpServletRequest request, HttpServletResponse response,
            Map parameters, JRDataSource conn) {
        try {
            JasperReport jasperReport = (JasperReport) JRLoader.loadObject(is);
            prepareReport(jasperReport, type);

            JasperPrint jasperPrint = JasperFillManager.fillReport(
                    jasperReport, parameters, conn);

            if (EXCEL_TYPE.equals(type)) {
                exportExcel(jasperPrint, defaultFilename, request, response);
            } else if (PDF_TYPE.equals(type)) {
                exportPdf(jasperPrint, defaultFilename, request, response);
            } else if (HTML_TYPE.equals(type)) {
                exportHtml(jasperPrint, defaultFilename, request, response);
            } else if (WORD_TYPE.equals(type)) {
                exportWord(jasperPrint, defaultFilename, request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 输出html静态页面,必须注入request和response
     * 
     * @param jasperPath
     * @param params
     * @param sourceList
     * @param imageUrl
     *            报表文件使用的图片路径,比如 ../servlets/image?image=
     * @throws JRException
     * @throws IOException
     * @throws ServletException
     */
    public static void showHtml(String defaultFilename, String reportfile,
            HttpServletRequest request, HttpServletResponse response, Map parameters,
            JRDataSource conn) throws JRException, IOException {


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");

        JRAbstractExporter exporter = getJRExporter(DocType.HTML);

        JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile,
                parameters, conn);
        request.getSession().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.IS_USING_IMAGES_TO_ALIGN,
        Boolean.FALSE);

        //设置图片文件存放路径,此路径为服务器上的绝对路径
        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();

        out.flush();

    }
    public static void showHtml(String defaultFilename, String reportfile,
            HttpServletRequest request, HttpServletResponse response, Map parameters,
            Connection conn) throws JRException, IOException {


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");

        JRAbstractExporter exporter = getJRExporter(DocType.HTML);

        JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile,
                parameters, conn);
        request.getSession().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.IS_USING_IMAGES_TO_ALIGN,
        Boolean.FALSE);
        //设置图片文件存放路径,此路径为服务器上的绝对路径
        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();
        out.flush();

    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void showPdf(String defaultFilename, String reportfile,
            HttpServletRequest request, HttpServletResponse response, Map parameters,
            JRDataSource conn) throws JRException, IOException {


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setContentType("application/pdf");

        JRAbstractExporter exporter = getJRExporter(DocType.PDF);

        JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile,
                parameters, conn);
        request.getSession().setAttribute(
                ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
                jasperPrint);

        OutputStream out = response.getOutputStream();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        exporter.exportReport();
        out.flush();

    }
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void showPdf(String defaultFilename, String reportfile,
            HttpServletRequest request, HttpServletResponse response, Map parameters,
            Connection conn) throws JRException, IOException {


        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setContentType("application/pdf");

        JRAbstractExporter exporter = getJRExporter(DocType.PDF);

        JasperPrint jasperPrint = JasperFillManager.fillReport(reportfile,
                parameters, conn);
        request.getSession().setAttribute(
                ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE,
                jasperPrint);

        OutputStream out = response.getOutputStream();

        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out);
        exporter.exportReport();
        out.flush();

    }

}

如果不是为了维护旧项目 并且只是为了导出excel 建议使用poi导出 poi灵活性更高一些并且更容易上手

你可能感兴趣的:(后端,Java,ireport,excel)