ireport导出各种格式(pdf,excel,word,html,print)

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(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) {
        session.setAttribute("REPORT_JASPERPRINT", jasperPrint);
        session.setAttribute("REPORT_FILENAME", report_fileName);
        session.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);

        session.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) {
                }
            }
        }
    }
}

 iReport+jasperReport之CSV、XML数据源

jasperReport支持多种格式的数据源,CSV(Comma Separated values),是一种用来存储数据的纯文本,文件格式,通常用于电子表格或数据库软件。

规则

0 开头是不留空,以行为单位。
1 可含或不含列名,含列名则居文件第一行。
2 一行数据不垮行,无空行。
3 以半角符号,作分隔符,列为空也要表达其存在。
4 列内容如存在,,则用“”包含起来。
5 列内容如存在“”则用“”“”包含。
6 文件读写时引号,逗号操作规则互逆。
7 内码格式不限,可为ASCII、Unicode或者其他。

jasper文件和前面几篇用到的是一样的(person.jasper),准备数据的文本文件Person.txt其中文件的格式对应模板文件的字段【 "pid", "name", "sex", "age", "password", "department"】。

"20000000001","bulktree1","man","21","1111111111","pcisv61"
"20000000002","bulktree2","man","22","2222222222","pcisv62"
"20000000003","bulktree3","man","23","3333333333","pcisv63"
"20000000004","bulktree4","man","24","4444444444","pcisv64"
"20000000005","bulktree5","man","25","5555555555","pcisv65"
"20000000006","bulktree6","man","26","6666666666","pcisv66"
"20000000007","bulktree7","man","27","7777777777","pcisv67"
"20000000008","bulktree8","man","28","8888888888","pcisv68"
"20000000009","bulktree9","man","29","9999999999","pcisv69"

下来我们看看jasperReport的API是怎么识别这些数据的,但是做这个之前我们还要指定数据到底是怎么对应的,定义String类型数组存放模板对应的列名和文本数据对应

String[] columNames  =   new  String[]  "pid""name""sex""age""password",
                
"department" }
;

识别这些数据并不难,下面这一句就可以搞定:

JRCsvDataSource jrcsvDataScource  =   new  JRCsvDataSource(JRLoader
                .getLocationInputStream(
" D:\\workspace\\Person.txt " ));

我们怎么才能让它识别对应的列呢?查看API看看对应的set方法吧!

//  set record delimiter
        jrcsvDataScource.setRecordDelimiter( " \r\n " );
        
//  set columnName
        jrcsvDataScource.setColumnNames(columNames);

至此数据源就准备完了,jasperReport封装了底层的实现,简单吧!下来看看完整的代码:

package  org.bulktree.ireport.csvdata;

import  java.util.HashMap;

import  net.sf.jasperreports.engine.JasperFillManager;
import  net.sf.jasperreports.engine.JasperPrint;
import  net.sf.jasperreports.engine.JasperReport;
import  net.sf.jasperreports.engine.data.JRCsvDataSource;
import  net.sf.jasperreports.engine.util.JRLoader;

import  org.bulktree.ireport.ViewReport;

public   class  CSVDataSource  {
    
    
public static void main(String[] args) {
        
try {
            
new CSVDataSource().reportView();
        }
 catch (Exception e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    
private void reportView() throws Exception {
        JasperReport jasperReport 
= (JasperReport) JRLoader
                .loadObject(
"D:\\workspace\\Person.jasper");

        JasperPrint jasperPrint 
= JasperFillManager.fillReport(jasperReport,
                getReportParameter(), getDateSource());
        
        
new ViewReport().viewer(jasperPrint);
    }


    
private HashMap getReportParameter() {
        HashMap parameters 
= new HashMap();
        parameters.put(
"reportTitle""laoshulin");
        
return parameters;
    }


    
private JRCsvDataSource getDateSource() throws Exception {
        String[] columNames 
= new String[] "pid""name""sex""age""password",
                
"department" }
;
        
// get csvdata
        JRCsvDataSource jrcsvDataScource = new JRCsvDataSource(JRLoader
                .getLocationInputStream(
"D:\\workspace\\test\\src\\org\\bulktree\\ireport\\csvdata\\Person.txt"));
        
// set record delimiter
        jrcsvDataScource.setRecordDelimiter("\r\n");
        
// set columnName
        jrcsvDataScource.setColumnNames(columNames);

        
return jrcsvDataScource;
    }

}

还是这样的效果吧!^_^

ireport导出各种格式(pdf,excel,word,html,print)_第1张图片

        至于XML数据源也是很简单,通过读取xml文件获得数据

Document document  =  JRXmlUtils.parse(JRLoader.getLocationInputStream(xmlFileName));

不同的是document会作为一个参数传递给报表,fillReport方法就不会出现第三个参数,完整代码如下:

package  org.bulktree.ireport.xmldata;

import  java.util.HashMap;
import  java.util.Locale;

import  net.sf.jasperreports.engine.JRException;
import  net.sf.jasperreports.engine.JRParameter;
import  net.sf.jasperreports.engine.JasperFillManager;
import  net.sf.jasperreports.engine.JasperPrint;
import  net.sf.jasperreports.engine.JasperReport;
import  net.sf.jasperreports.engine.query.JRXPathQueryExecuterFactory;
import  net.sf.jasperreports.engine.util.JRLoader;
import  net.sf.jasperreports.engine.util.JRXmlUtils;

import  org.bulktree.ireport.ViewReport;
import  org.w3c.dom.Document;

public   class  XMLDataSource  {

    
private static final String JASPER_FILE_NAME = "D:\\workspace\\Person.jasper";
    
private static final String XML_FILE_NAME = "D:\\workspace\\person.xml";

    
private void viewerReport() throws JRException {
        JasperReport jasperReport 
= (JasperReport) JRLoader.loadObject(JASPER_FILE_NAME);

        JasperPrint jasperPrint 
= JasperFillManager.fillReport(jasperReport,
                getReportParameter(XML_FILE_NAME));

        
new ViewReport().viewer(jasperPrint);
    }


    
private HashMap getReportParameter(String xmlFileName) {
        HashMap parameters 
= new HashMap();
        
try {
            parameters.put(
"reportTitle""laoshulin");
            Document document 
= JRXmlUtils.parse(JRLoader.getLocationInputStream(xmlFileName));

            parameters.put(JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT,
                    document);
            parameters.put(JRXPathQueryExecuterFactory.XML_DATE_PATTERN, 
"yyyy-MM-dd");
            parameters.put(JRXPathQueryExecuterFactory.XML_NUMBER_PATTERN, 
"#,##0.##");
            parameters.put(JRXPathQueryExecuterFactory.XML_LOCALE, Locale.CHINESE);
            parameters.put(JRParameter.REPORT_LOCALE, Locale.CHINA);

        }
 catch (JRException e) {
            
// TODO Auto-generated catch block
            e.printStackTrace();
        }


        
return parameters;
    }


    
public static void main(String[] args) throws Exception {
        
new XMLDataSource().viewerReport();
    }

}

        预览效果就不看了吧!哈哈 都是一样的道理,现在看看jasperReport的API有多强大了吧!

你可能感兴趣的:(IREPORT)