文档章节

JasperReport報表的使用示例

罗码码
 罗码码
发布于 2016/08/25 14:57
字数 925
阅读 239
收藏 0

JasperReport的Util類

package mo.gov.dsat.vss.report.util;

/**
 * @Project Name: vss-rpt-core
 * @File Name: JasperReportFill.java
 * @Package Name: mo.gov.dsat.vss.report
 * @Date: 16/05/2016 3:11:29 PM
 * @Copyright: Copyright (c) 2016 Atos Information Technology HK Limited. All Rights Reserved.
 */

import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.DefaultJasperReportsContext;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReportsContext;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;


public class JasperReportUtils {

    public static void exportReportToPdf(InputStream inputStream, OutputStream outputStream, Map<String, Object> parameters, JRDataSource dataSource) throws Exception {
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters, dataSource);
        JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
    }

    /**
     * 多張.jasper 報表一起打印.
     *
     * @param inputStream
     * @param outputStream
     * @param parameters
     * @param dataSource
     * @throws Exception
     */
    public static void exportReportToPdf(List<FillReportInfo> fillReportInfos, OutputStream outputStream, Map<String, Object> parameters) throws Exception {
        List<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
        for (FillReportInfo info : fillReportInfos) {
            JasperPrint jasperPrint = JasperFillManager.fillReport(info.getInputStream(), parameters,info.getDataSource());
            jasperPrintList.add(jasperPrint);
        }
        JasperReportsContext jasperReportsContext = DefaultJasperReportsContext.getInstance();
        JRPdfExporter exporter = new JRPdfExporter(jasperReportsContext);

        exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));

        exporter.exportReport();
    }

    public static void exportReportToPdf(InputStream inputStream, OutputStream outputStream, Map<String, Object> parameters, Connection connection) throws Exception {
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters, connection);
        JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
    }

    public static void exportReportToHtml(InputStream inputStream, OutputStream outputStream, Map<String, Object> parameters) throws Exception {
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters);

        HtmlExporter exporter = new HtmlExporter();
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleHtmlExporterOutput(outputStream));
        exporter.exportReport();
    }

    public static void exportReportToXml(InputStream inputStream, OutputStream outputStream, Map<String, Object> parameters) throws Exception {
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters);
        JasperExportManager.exportReportToPdfStream(jasperPrint, outputStream);
    }

    public static String exportReportToXml(InputStream inputStream, Map<String, Object> parameters) throws Exception {
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters);

        return JasperExportManager.exportReportToXml(jasperPrint);
    }

    /**
     * 導出 2007以後的Word文檔,後綴名 docx.
     *
     * @param inputStream
     * @param outputStream
     * @param parameters
     * @param dataSource
     * @throws Exception
     */
    public static void exportReportToWord(InputStream inputStream, OutputStream outputStream, Map<String, Object> parameters, JRDataSource dataSource) throws Exception {
        JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream, parameters, dataSource);
        DefaultJasperReportsContext jasperReportsContext = DefaultJasperReportsContext.getInstance();

        JRDocxExporter exporter = new JRDocxExporter(jasperReportsContext);

        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));

        exporter.exportReport();
    }
    
    /**
     * 多張.jasper 報表一起打印.
     *
     * @param inputStream
     * @param outputStream
     * @param parameters
     * @param dataSource
     * @throws Exception
     */
    public static void exportReportToWord(List<FillReportInfo> fillReportInfos, OutputStream outputStream, Map<String, Object> parameters) throws Exception {
        List<JasperPrint> jasperPrintList = new ArrayList<JasperPrint>();
        for (FillReportInfo info : fillReportInfos) {
            JasperPrint jasperPrint = JasperFillManager.fillReport(info.getInputStream(), parameters,info.getDataSource());
            jasperPrintList.add(jasperPrint);
        }
        JasperReportsContext jasperReportsContext = DefaultJasperReportsContext.getInstance();
        //導出 2007以後的Word文檔,後綴名 docx.
        JRDocxExporter exporter = new JRDocxExporter(jasperReportsContext);

        exporter.setExporterInput(SimpleExporterInput.getInstance(jasperPrintList));
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(outputStream));

        exporter.exportReport();
    }

    public static class FillReportInfo {
        private InputStream inputStream;
        private JRDataSource dataSource;
        public InputStream getInputStream() {
            return inputStream;
        }
        public FillReportInfo setInputStream(InputStream inputStream) {
            this.inputStream = inputStream;
            return this;
        }
        public JRDataSource getDataSource() {
            return dataSource;
        }
        public FillReportInfo setDataSource(JRDataSource dataSource) {
            this.dataSource = dataSource;
            return this;
        }
    }
}

 

=====================================================================

打印服務類

package mo.gov.dsat.vss.rpt;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import mo.gov.dsat.vss.report.util.JasperReportUtils;
import mo.gov.dsat.vss.report.util.JasperReportUtils.FillReportInfo;
import mo.gov.dsat.vss.txi.data.dto.TaxiLicInstructionsDTO;
@Service
@Transactional
public class TaxiLicCurrentServiceImpl implements ITaxiLicCurrentService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TaxiLicCurrentServiceImpl.class);
    
    /**
     * jasper單個報表打印
     */
    @Override
    public void licCurrent(List<TaxiLicInstructionsDTO> list,OutputStream outputStream) {
        Map<String,Object> parameters=new HashMap<String,Object>();
        
        JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(list);
        // 讀取vss_lic_current.jasper
        InputStream inputStream =  TaxiLicCurrentServiceImpl.class.getResourceAsStream("/template/vss_lic_current_two.jasper");
        
        // 定義報表的參數
        try {
            JasperReportUtils.exportReportToWord(inputStream, outputStream, parameters, beanCollectionDataSource);
        } catch (Exception e) {
            LOGGER.error("打印失敗",e);
            e.printStackTrace();
        }
    }
    
    /**
     * 多張.jasper 報表一起打印.
     * @param list
     * @param outputStream
     */
    @Override
    public void licCurrentAndLicInstructions(List<TaxiLicInstructionsDTO> list,OutputStream outputStream){
        String taxiMortgage ="";
        String taxiMortgageP ="";
        Map<String,Object> parameters=new HashMap<String,Object>();
        for(TaxiLicInstructionsDTO dto : list){
            if(!StringUtils.isBlank(dto.getTaxiMortEntity1())){
                String[] str = dto.getTaxiMortEntity1().split("-");
                taxiMortgage = str[0].trim();
                taxiMortgageP = str[1].trim();
                parameters.put("MortCName", taxiMortgage);
                parameters.put("MortPName", taxiMortgageP);
            }else if(!StringUtils.isBlank(dto.getTaxiMortEntity2())){
                String[] str = dto.getTaxiMortEntity2().split("-");
                taxiMortgage = str[0].trim();
                taxiMortgageP = str[1].trim();
                parameters.put("MortCName", taxiMortgage);
                parameters.put("MortPName", taxiMortgageP);
            }else if(StringUtils.isBlank(dto.getTaxiMortEntity1()) && StringUtils.isBlank(dto.getTaxiMortEntity2())){
                taxiMortgage = "";
                taxiMortgageP="";
                parameters.put("MortCName", taxiMortgage);
                parameters.put("MortPName", taxiMortgageP);
            }
        }
        
        List<FillReportInfo> fillReportInfos=new ArrayList<FillReportInfo>();
        
        //第一個jasperReport(牌照現況說明(查車紙))
        JRBeanCollectionDataSource beanCollectionDataSource2 = new JRBeanCollectionDataSource(list);
        // 讀取vss_lic_current.jasper
        InputStream inputStream2 =  TaxiLicCurrentServiceImpl.class.getResourceAsStream("/template/vss_lic_current_two.jasper");
        
        FillReportInfo info2=new FillReportInfo();
        info2.setDataSource(beanCollectionDataSource2);
        info2.setInputStream(inputStream2);
        fillReportInfos.add(info2);
        
        //第二個jasperReport(牌     照     現     況     說     明)
        JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(list);
        // 讀取vss_lic_current.jasper
        InputStream inputStream = null;
        if(StringUtils.isBlank(taxiMortgage) && StringUtils.isBlank(taxiMortgageP)){
            inputStream =  TaxiLicInstructionsServiceImpl.class.getResourceAsStream("/template/vss_lic_current.jasper");
        }else{
            inputStream =  TaxiLicInstructionsServiceImpl.class.getResourceAsStream("/template/vss_lic_currentAndMort.jasper");
        }
        FillReportInfo info=new FillReportInfo();
        info.setDataSource(beanCollectionDataSource);
        info.setInputStream(inputStream);
        fillReportInfos.add(info);
        
        // 定義報表的參數
        try {
            JasperReportUtils.exportReportToWord(fillReportInfos, outputStream, parameters);
        } catch (Exception e) {
            LOGGER.error("打印失敗",e);
            e.printStackTrace();
        }
        
    }
    
}

============================================================================

Action調用,這裡的 outputStream 有文件名稱和彈出選擇路徑傳入進去

/**
     * 牌照現況說明(查車紙)和 的士准牌照現況聲明書 一起打印
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public String licCurrentAndLicInstructions() throws IOException{
        TaxiLicenseQuery query = new TaxiLicenseQuery();
        TaxiLicenseDTO dto = new TaxiLicenseDTO();
        dto.setTaxiLicId(Long.valueOf(model.get("taxiLicId").toString()));
        query.setTaxiLicenseDTO(dto);
        CollectionDTO coll = (CollectionDTO) licService.LicInstructions(query);
        if(coll!=null&&!coll.getDtos().isEmpty()){
            //SysParamsConstant.getParamValue("RPT_POFIX_DATE_TIME_FORMAT"))從數據庫獲取一個格式把時間格式化成這這種格式
            String fileName = DateUtil.format(new Date(),SysParamsConstant.getParamValue("RPT_POFIX_DATE_TIME_FORMAT"))+".doc";
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType("application/force-download");
            response.setHeader("Content-Transfer-Encoding", "binary");
            response.setHeader("Content-Disposition","attachment; filename=\"" +fileName+ "\"");
            OutputStream outputStream = response.getOutputStream();
            currentService.licCurrentAndLicInstructions(((List<TaxiLicInstructionsDTO>) coll.getDtos()),outputStream);
            outputStream.flush();
            outputStream.close();
        }else{
            LOGGER.error("沒有找到要打印的數據...");
        }
        return null;
    }

© 著作权归作者所有

共有 人打赏支持
罗码码
粉丝 0
博文 154
码字总数 41577
作品 0
珠海
高级程序员
私信 提问
可视化报表设计工具--iReport

iReport是用于定义JasperReport报表的可视化工具,JasperReport使用XML来定义一个报表的结构,iReport可以让用户很方便地定义报表,而不需要手工去写这些XML文件。 iReport是为JasperReports...

匿名
2008/09/20
42.9K
4
在Windows Server 2008 R2上部署ASP.NET MVC应用

OS: Windows Server 2008 R2 .NET: 4.0 (1) 安装IIS 打开管理工具 > 服务器管理, 选择角色 > 添加角色 勾选Web服务器选项 选择除FTP外的角色服务(可选) (2) 安装Web Deployment 安装方式选择...

南風
2014/08/21
0
0
李雯 2018-6-5 工作日报

8:00~9:30 業務内容: 自动导入本味网络订单 检查快递状态,修改订单状态 9:30~12:00 整理制作2018-5友利売上報告表 午休1.5小时 13:30~16:00 業務内容: 整理制作2018-5友利売上報告表,处理...

ribunn
2018/06/05
0
0
李雯 2018-7-23 工作日报

8:00~9:00 業務内容: 自动导入本味网络订单 检查快递状态,修改订单状态 9:00~12:00 業務内容: 根据2018-06友利売上報告表到友利系统录入本味主義Alipay部分入金伝票 13:30~16:00 業務内容:...

ribunn
2018/07/23
0
0
李雯 2018-7-26 工作日报

8:00~9:00 業務内容: 自动导入本味网络订单 检查快递状态,修改订单状态 9:00~12:00 業務内容: 根据2018-06友利売上報告表到友利系统录入楽天部分入金伝票 13:30~16:00 業務内容: 根据2018-...

ribunn
2018/07/26
0
0

没有更多内容

加载失败,请刷新页面

加载更多

php register_globals将接收参数转为全局变量

最近在看公司旧的系统的时候发现一个很奇怪的事情,很多页面用的变量找不到源头,没有定义也不是接收,意思是腾空出现的。 经排查,原来是php配置做的好事:register_globals = On。registe...

shikamaru
29分钟前
9
0
Linux 交换分区swap

一、创建和启用swap交换区 如果你的服务器的总是报告内存不足,并且时常因为内存不足而引发服务被强制kill的话,在不增加物理内存的情况下,启用swap交换区作为虚拟内存是一个不错的选择,我...

Yue_Chen
31分钟前
3
0
notepad++如何使用列块编辑模式?

notepad++如何使用列块编辑模式? 听语音 | 浏览:18584 | 更新:2015-12-22 10:56 | 标签:软件 1 2 3 4 5 6 7 分步阅读 notepad++是一款功能强大的文本编辑器,可以支持各种不同的文本类型...

linjin200
33分钟前
1
0
Java 基础语法

一个Java程序可以认为是一系列对象的集合,而这些对象通过调用彼此的方法来协同工作。下面简要介绍下类、对象、方法和实例变量的概念。 对象:对象是类的一个实例,有状态和行为。例如,一条...

二九结狐六体
37分钟前
3
0
研发团队资源成本优化实践

背景 工程师主要面对的是技术挑战,更关注技术层面的目标。研发团队的管理者则会把实现项目成果和业务需求作为核心目标。实际项目中,研发团队所需资源(比如物理机器、内存、硬盘、网络带宽...

美团技术团队
41分钟前
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部