ExportServlet

Web.xml

<servlet>
        <servlet-name>ExportServlet</servlet-name>
        <servlet-class>
            com.XXXX.oss.jasperreports.utils.ExportServlet
        </servlet-class>

</servlet>

 <servlet-mapping>
       <servlet-name>ExportServlet</servlet-name>
       <url-pattern>/jasperreports/commons/export</url-pattern>
</servlet-mapping>

ExportServlet.java

package com.XXXX.oss.jasperreports.utils;

import java.io.IOException;

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

import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.j2ee.servlets.ImageServlet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author  king
 * @date 20120201
 */


public class ExportServlet extends HttpServlet {

    private Log log = LogFactory.getLog(ExportServlet.class);

    private static final long serialVersionUID = 1626331706517382929L;

    @Override
    protected void service(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        JasperPrint jasperPrint = (JasperPrint) request.getSession()
                .getAttribute(
                        ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE);

        if (jasperPrint == null) {
            throw new ServletException("请先进行报表查询!");
        }

        response.setHeader("Content-Disposition", "attachment;filename=" + "report.xls");
        //response.setHeader("Content-Disposition", "filename=" + "report.xls");
        
        response.setCharacterEncoding("GBK");

        //response.setContentType("application/vnd.ms-excel");
        
        response.setContentType("application/x-msdownload");

        ServletOutputStream os = response.getOutputStream();

        JRXlsExporter xlsExporter = new JRXlsExporter();

        xlsExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);

        xlsExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);

        xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);

        xlsExporter.setParameter(
                JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.FALSE);

        try {
            xlsExporter.exportReport();

            os.flush();
            os.close();
        } catch (Exception e) {
            log.error("", e);
            throw new ServletException("导出数据出错:" + e.getMessage());
        }
    }

}



你可能感兴趣的:(exception,Date,session,Stream,service,报表)