JBOSS 点滴

丰丰的博客

IREPORT报表实现

一、在JSP中通过传参数实现源代码:(在jasper模板中定义好查询条件及参数)


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.io.*,java.sql.*,net.sf.jasperreports.engine.*"%>
<%@ page import="com.szywit.dbapi.dbconn.CPool,net.sf.jasperreports.engine.data.JRBeanCollectionDataSource,net.sf.jasperreports.engine.util.JRLoader"%>
<jsp:directive.include file="/public_jdbc.jspf" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>报表打印</title>
</head>

<body id="Body">
    
<%
        String parentid 
= "",sect_name="",actcode="",run_types="";
        CommonModel CM;
        String reportName 
= request.getParameter("reportName");
        
if (request.getParameter("parentid"!= null)
            parentid 
= request.getParameter("parentid");
        
if (request.getParameter("pect_name"!= null)
            sect_name 
= request.getParameter("pect_name");
        
if (request.getParameter("actcode"!= null)
            actcode 
= request.getParameter("actcode");
        
if (request.getParameter("run_types"!= null)
            run_types 
= request.getParameter("run_types");

        
//报表编译之后的.jasper文件的存放位置
        File reportFile = new File(
                application.getRealPath(
"/ems/report/eventLog.jasper"));
        
//传递报表中用到的参数值,这里是空值
        System.out.println("param:=" + parentid);
        Map parameters 
= new HashMap();
        System.out.print(sect_name);
                   parameters.put(
"event_code""%"+event_code+"%");
           parameters.put(
"event_name",  "%"+event_name+"%");
           parameters.put(
"type_code2",  "%"+parentid+"%");
        
        
        
           parameters.put(
"type_code""%"+parentid+"%");
           parameters.put(
"type_code1",  "%"+parentid+"%");
           parameters.put(
"type_code2",  "%"+parentid+"%");
           
           parameters.put(
"sect_name",  "%"+sect_name+"%");
           parameters.put(
"actcode",  "%"+actcode+"%");
           parameters.put(
"run_types",  "%"+run_types+"%");

        
//连接到数据库
        Connection conn = null;
        
try {
            conn 
= ConnectionManager.getConnection("EMSDATACON");
        }
 catch (Exception e) {
            e.printStackTrace();
            
throw new Exception("创建默认数据库连接不成功,请检查dbconn.properties是否正确配置");
        }

        System.out.println(
"----------jasper begin-----------");
        
//在控制台打印报表文件的物理路径 
        System.out.println("****物理路径 ***" + reportFile.getPath());
        
byte[] bytes = JasperRunManager.runReportToPdf(
                reportFile.getPath(), parameters, conn);
            
                
        System.out.println(
"bytes=" + parameters);
        System.out.println(
"---------jasper end-------");
        response.setContentType(
"application/pdf");
        response.setContentLength(bytes.length);

        
//清除输出对象的冲突(因jsp本身有自己的out输出对象,如果去除下面的语句,则response.getOutputStream()得到的输出对象与原来存在的out对象冲突,会报异常)

        out.clear();
        out 
= pageContext.pushBody();

        ServletOutputStream output 
= response.getOutputStream();
        output.write(bytes, 
0, bytes.length);
        output.flush();
        output.close();

        
try {
            
if (conn != null{
                conn.close();
            }

        }
 catch (Exception e) {
            e.printStackTrace();
        }

    
%>
</body>
</html>

二、通过传递结果集,JAVA实现

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%@ page language="java" import="com.szywit.file.ReportExport"%>
<%@ page
    
import="java.io.*,net.sf.jasperreports.engine.*,
net.sf.jasperreports.engine.util.JRLoader,net.sf.jasperreports.engine.data.JRBeanCollectionDataSource,net.sf.jasperreports.engine.export.JRRtfExporter"%>
<jsp:directive.include file="/public_jdbc.jspf" />
<%
    String parentid 
= "", sect_name = "", actcode = "", run_types = "", types = "", typedot = "";
    List list 
= new ArrayList();
    File reportFile 
= new File(
            application.getRealPath(
"/ems/report/preschDetail.jasper"));

    Vector rsVector;
    CommonModel CM;

    
//传参
    if (request.getParameter("types"!= null)
        types 
= request.getParameter("types");
    
if (request.getParameter("parentid"!= null)
        parentid 
= request.getParameter("parentid");
    
if (request.getParameter("pect_name"!= null)
        sect_name 
= request.getParameter("pect_name");
    
if (request.getParameter("actcode"!= null)
        actcode 
= request.getParameter("actcode");
    
if (request.getParameter("run_types"!= null)
        run_types 
= request.getParameter("run_types");

    String sql 
= "select  * from vw_preschdetail  where ( type_code like '%"
            
+ parentid
            
+ "%'"
            
+ "or type_code2 like   '%"
            
+ parentid
            
+ "%'  or type_code1 like   '%"
            
+ parentid
            
+ "%')"
            
+ "and (sect_name like  '%"
            
+ sect_name
            
+ "%')  and (run_types like   '%"
            
+ run_types
            
+ "%')"
            
+ " and (actcode like   '%" + actcode + "%')";

    
try {
        rsVector 
= CCommonDAO.select(sql, "EMSDATACON");
        
if (rsVector != null && !rsVector.isEmpty()) {
            
for (int j = 0; j < rsVector.size(); j++{
                CM 
= (CommonModel) rsVector.get(j);
                Map map 
= new HashMap();
                map.put(
"sect_names", CM.getAttrValue("sect_names")
                        .trim());
                map.put(
"type_name", CM.getAttrValue("type_name")
                        .trim());
                map.put(
"actcode", CM.getAttrValue("actcode").trim());
                map.put(
"actconts", CM.getAttrValue("actconts").trim());
                map.put(
"run_types", CM.getAttrValue("run_types")
                        .trim());
                map.put(
"car_lens", CM.getAttrValue("car_lens").trim());

                map.put(
"dev_info", CM.getAttrValue("dev_info").trim());
                map.put(
"vehi_info", CM.getAttrValue("vehi_info")
                        .trim());
                map.put(
"vehisplit_info",
                        CM.getAttrValue(
"vehisplit_info").trim());
                map.put(
"car_lens", CM.getAttrValue("car_lens").trim());
                map.put(
"pub_info", CM.getAttrValue("pub_info").trim());
                list.add(map);
            }

        }


        String filenames 
= "预案台帐"
                
+ CAutoSerialNumber.getServerDateTime();
        
//String filenames = "预案台帐." + typedot;
        ReportExport.export(list, filenames, types, reportFile,
                request, response);
/*         out.clear();
        out = pageContext.pushBody(); 
*/

        
/*         JRDataSource ds = new JRBeanCollectionDataSource(list, false);
         JasperReport jasperReport = (JasperReport) JRLoader
         .loadObject(reportFile);
         Map parameters = new HashMap();
         JasperPrint jasperPrint = JasperFillManager.fillReport(
         jasperReport, parameters, ds);

         response.setContentType("application/msword;charset=utf-8");
         String files = "预案台帐" + CAutoSerialNumber.getServerDateTime() + ".doc";
         String fileName = new String(files.getBytes("GBK"), "ISO8859_1");
         response.setHeader("Content-disposition",
         "attachment; filename=" + fileName);
        
         OutputStream os=response.getOutputStream();   

         JRExporter exporter = new JRRtfExporter();
         exporter.setParameter(JRExporterParameter.JASPER_PRINT,
         jasperPrint);
         exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
         os);

         exporter.exportReport();
        
        

         out.clear();   
         out = pageContext.pushBody();  
*/


    }
 catch (Exception e) {
        e.printStackTrace();

    }

%>

JAVA代码

package com.szywit.file;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

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

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.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
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.util.JRLoader;

/**
 * 按照类型导出不同格式文件
 * 
 * 
@param datas
 *            数据
 * 
@param type
 *            文件类型
 * 
@param is
 *            jasper文件的来源
 * 
@param request
 * 
@param response
 
*/


public class ReportExport {
    
public static void prepareReport(JasperReport jasperReport, String type) {
        
/*
         * 如果导出的是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 filename,
            HttpServletRequest request, HttpServletResponse response)
            
throws IOException, JRException {
        
/*
         * 设置头信息
         
*/

        
if (filename.trim() != null && filename != null{
            filename 
= filename + ".xls";
        }
 else {
            filename 
= "export.xls";
        }

            
        response.setContentType(
"application/vnd.ms-excel");
        String fileName 
= new String(filename.getBytes("GBK"), "ISO8859_1");
        response.setHeader(
"Content-disposition""attachment; filename="
                
+ fileName);

        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);
        exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND,
                Boolean.FALSE);
        exporter.exportReport();
        ouputStream.flush();
        ouputStream.close();
    }


    
/**
     * 导出pdf,注意此处中文问题, 1)在ireport的classpath中加入iTextAsian.jar
     * 2)在ireport画jrxml时,pdf font name :STSong-Light ,pdf encoding :
     * UniGB-UCS2-H
     
*/

    
public static void exportPdf(JasperPrint jasperPrint,
            HttpServletRequest request, HttpServletResponse response)
            
throws IOException, JRException {
        response.setContentType(
"application/pdf");
        String fileName 
= new String("未命名.pdf".getBytes("GBK"), "ISO8859_1");
        response.setHeader(
"Content-disposition""attachment; filename="
                
+ fileName);
        ServletOutputStream ouputStream 
= response.getOutputStream();
        JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }

    
/**
     * 在线显示pdf,
     
*/

    
public static void exportLinePdf(JasperPrint jasperPrint,String defaultFilename,
            HttpServletRequest request, HttpServletResponse response)
            
throws IOException, JRException {
    
        String defaultname 
= null;
        
try {
            response.setContentType(
"application/pdf");
            response.setCharacterEncoding(
"UTF-8");
            
if (defaultFilename.trim() != null && defaultFilename != null{
                defaultname 
= defaultFilename + ".pdf";
            }
 else {
                defaultname 
= "export.pdf";
            }

            response.setHeader(
"Content-disposition""inline; filename="+defaultname);
            ServletOutputStream ouputStream 
= response.getOutputStream();
            JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream);
            ouputStream.flush();
            ouputStream.close();
        }
 catch (Exception e) {
            System.out.println(
"Jasper Output Error:" + e.getMessage());
        }

    }



    
/**
     * 导出html
     
*/

    
public static void exportHtml(JasperPrint jasperPrint,
            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);

        exporter.exportReport();

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


    
/**
     * 导出word
     
*/

    
public static void exportWord(JasperPrint jasperPrint,String filename,
            HttpServletRequest request, HttpServletResponse response)
            
throws JRException, IOException {
        
if (filename.trim() != null && filename != null{
            filename 
= filename + ".xls";
        }
 else {
            filename 
= "export.xls";
        }

        response.setContentType(
"application/msword;charset=utf-8");
        String fileName 
= new String(filename.getBytes("GBK"), "ISO8859_1");
        response.setHeader(
"Content-disposition""attachment; filename="
                
+ fileName);
        ServletOutputStream ouputStream 
= response.getOutputStream();
        JRExporter exporter 
= new JRRtfExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM,
                ouputStream);

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


    
/**
     * 打印
     
*/

    
public static void exportPrint(JasperPrint jasperPrint,
            HttpServletResponse response, HttpServletRequest request)
            
throws IOException {
        response.setContentType(
"application/octet-stream");
        ServletOutputStream ouputStream 
= response.getOutputStream();
        ObjectOutputStream oos 
= new ObjectOutputStream(ouputStream);
        oos.writeObject(jasperPrint);
        oos.flush();
        oos.close();
        ouputStream.flush();
        ouputStream.close();
    }


    
public static void export(Collection datas,String filename, String type, File is,
            HttpServletRequest request, HttpServletResponse response) 
{
        
try {
            JasperReport jasperReport 
= (JasperReport) JRLoader.loadObject(is);
            prepareReport(jasperReport, type);
            JRDataSource ds 
= new JRBeanCollectionDataSource(datas, false);
            Map parameters 
= new HashMap();
            JasperPrint jasperPrint 
= JasperFillManager.fillReport(
                    jasperReport, parameters, ds);

            
if (EXCEL_TYPE.equals(type)) {
                exportExcel(jasperPrint,filename,request, response);
            }
 else if (PDF_TYPE.equals(type)) {
                exportPdf(jasperPrint, request, response);
            }
 else if (HTML_TYPE.equals(type)) {
                exportHtml(jasperPrint, request, response);
            }
 else if (WORD_TYPE.equals(type)) {
                exportWord(jasperPrint, filename,request, response);
            }
else if (LINE_TYPE.equals(type)) {
                exportLinePdf(jasperPrint,filename,request, response);
            }

        }
 catch (Exception e) {
            e.printStackTrace();
        }

    }


    
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 final String LINE_TYPE = "linePdf";

}




 

posted on 2014-11-19 11:47 半导体 阅读(371) 评论(0)  编辑  收藏 所属分类: 报表


只有注册用户登录后才能发表评论。


网站导航: