iReport简单示例

本文介绍了如何使用JasperReports框架创建报表并进行展示与打印的过程,包括设置布局、添加按钮触发打印功能以及处理数据源等关键步骤。
package ireport;

import javax.swing.JFrame;
import java.awt.BorderLayout;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

import com.bestway.bcus.client.common.CustomReportDataSource;
import com.bestway.bcus.client.common.DgReportViewer;

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

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class IReportTest extends JFrame {
    public IReportTest() {
        
        this.setBounds(300, 240, 300, 240);
        
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        getContentPane().setLayout(new BorderLayout(0, 0));
        
        JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.CENTER);
        panel.setLayout(null);
        
        JButton btnNewButton = new JButton("\u6253\u5370\u62A5\u8868");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                printReport();
            }
        });
        btnNewButton.setBounds(94, 97, 93, 23);
        panel.add(btnNewButton);
        
    }
    
    public void printReport(){
        
        try {
            
            CustomReportDataSource ds = new CustomReportDataSource(
                    getList());
            
            CustomReportDataSource dss = new CustomReportDataSource(
                    getList());
            
            InputStream masterReportStream = IReportTest.class
                    .getResourceAsStream("Untitled_report_1.jasper");
            InputStream commInfoReportStream = IReportTest.class
                    .getResourceAsStream("Untitled_report_1_subreport0.jasper");
            
            JasperReport commInfoReport = (JasperReport) JRLoader
                    .loadObject(commInfoReportStream);
            
            Map<String, Object> parameters = new HashMap<String, Object>();
            parameters.put("commInfoReport", commInfoReport);
            parameters.put("IReportTest", "测试");
            parameters.put("list", dss);
            
            System.out.println("masterReportStream=="+masterReportStream+"  parameters=="+parameters+"  ds=="+ds);
            
            JasperPrint jasperPrint = JasperFillManager.fillReport(
                    masterReportStream, parameters, ds);
            
            DgReportViewer viewer = new DgReportViewer(jasperPrint);
            viewer.setVisible(true);
            
        } catch (JRException e) {
            e.printStackTrace();
        }
    }
    
    public List getList(){
        List list = new ArrayList();
        list.add(new Student("10001","张三","男","java",20));
        list.add(new Student("10002","李四","女","C#",20));
        list.add(new Student("10003","王五","男","C++",20));
        list.add(new Student("10004","赵六","女","html",20));
return list;
    }
    
    public class Student{
        private String id;
        private String name;
        private String sex;
        private String hobby;
        private Integer age;
        
        public Student(String id,String name,String sex,String hobby,Integer age){
            this.id = id;
            this.name = name;
            this.sex = sex;
            this.hobby = hobby;
            this.age = age;
        }
        
        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        public String getHobby() {
            return hobby;
        }

        public void setHobby(String hobby) {
            this.hobby = hobby;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new IReportTest().setVisible(true);
            }
        });
    }
}
/*
 * Created on 2004-8-28
 *
 * //
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.bestway.bcus.client.common;

import java.awt.BorderLayout;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JPanel;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.view.JRSaveContributor;
import net.sf.jasperreports.view.JRViewer;

import com.bestway.client.windows.form.FmMain;

/**
 * @author Administrator // change the template for this generated type comment
 *         go to Window - Preferences - Java - Code Style - Code Templates
 */
public class DgReportViewer extends JDialog {
    private static final long serialVersionUID = 1L;

    private JRViewer viewer = null;

    private JPanel pnlMain = null;

    /** Creates new form DgReportViewer */
    public DgReportViewer(String sourceFile, boolean isXMLFile, boolean isModal)
            throws JRException {
        super(FmMain.getInstance());
        this.setModal(isModal);
        initComponents();
        this.viewer = new JRViewer(sourceFile, isXMLFile);
        removeJRSaveContributor();
        this.pnlMain.add(this.viewer, BorderLayout.CENTER);
    }

    /** Creates new form DgReportViewer */
    public DgReportViewer(String sourceFile, boolean isXMLFile)
            throws JRException {
        this(sourceFile, isXMLFile, true);
    }

    /** Creates new form DgReportViewer */
    public DgReportViewer(InputStream is, boolean isXMLFile, boolean isModal)
            throws JRException {
        super(FmMain.getInstance());
        this.setModal(isModal);
        initComponents();
        this.viewer = new JRViewer(is, isXMLFile);
        removeJRSaveContributor();
        this.pnlMain.add(this.viewer, BorderLayout.CENTER);
    }

    /** Creates new form DgReportViewer */
    public DgReportViewer(InputStream is, boolean isXMLFile) throws JRException {
        this(is, isXMLFile, true);
    }

    /** Creates new form DgReportViewer */
    public DgReportViewer(JasperPrint jasperPrint, boolean isModal)
            throws JRException {
        super(FmMain.getInstance());
        initComponents();
        this.setModal(isModal);
        this.viewer = new JRViewer(jasperPrint);
        removeJRSaveContributor();
        this.pnlMain.add(this.viewer, BorderLayout.CENTER);
    }

    /** Creates new form DgReportViewer */
    public DgReportViewer(JasperPrint jasperPrint) throws JRException {
        this(jasperPrint, true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    private void initComponents() {
        setTitle("报表预览");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });
        pnlMain = new javax.swing.JPanel();
        pnlMain.setLayout(new java.awt.BorderLayout());
        getContentPane().add(pnlMain, java.awt.BorderLayout.CENTER);
        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit()
                .getScreenSize();
        setSize(new java.awt.Dimension(screenSize.width, screenSize.height - 25));
        this
                .setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
    }

    public void setVisible(boolean b) {
        this.setLocation(0, 0);
        super.setVisible(b);
    }

    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_exitForm
        this.setVisible(false);
        this.viewer.clear();
        this.viewer = null;
        this.getContentPane().removeAll();
    }

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String args[]) {
        String fileName = null;
        boolean isXMLFile = false;

        // if (args.length == 0) {
        // usage();
        // return;
        // }

        int k = 0;
        while (args.length > k) {
            if (args[k].startsWith("-F"))
                fileName = args[k].substring(2);
            if (args[k].startsWith("-XML"))
                isXMLFile = true;

            k++;
        }

        try {
            viewReport("d:/myjrprint.jrprint", false);
        } catch (JRException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    /**
     * 
     */
    private static void usage() {
        System.out.println("DgReportViewer usage:");
        System.out.println("\tjava DgReportViewer -XML -Ffile");
    }

    /**
     * 
     */
    public static void viewReport(String sourceFile, boolean isXMLFile)
            throws JRException {
        DgReportViewer jasperViewer = new DgReportViewer(sourceFile, isXMLFile,
                true);
        jasperViewer.setVisible(true);
    }

    /**
     * 
     */
    public static void viewReport(InputStream is, boolean isXMLFile)
            throws JRException {
        DgReportViewer jasperViewer = new DgReportViewer(is, isXMLFile, true);
        jasperViewer.setVisible(true);
    }

    /**
     * 
     */
    public static void viewReport(JasperPrint jasperPrint) throws JRException {
        DgReportViewer jasperViewer = new DgReportViewer(jasperPrint, true);
        jasperViewer.setVisible(true);
    }

    /**
     * 
     */
    public static void viewReport(String sourceFile, boolean isXMLFile,
            boolean isModal) throws JRException {
        DgReportViewer jasperViewer = new DgReportViewer(sourceFile, isXMLFile,
                isModal);
        jasperViewer.setVisible(true);
    }

    /**
     * 
     */
    public static void viewReport(InputStream is, boolean isXMLFile,
            boolean isModal) throws JRException {
        DgReportViewer jasperViewer = new DgReportViewer(is, isXMLFile, isModal);
        jasperViewer.setVisible(true);
    }

    /**
     * 
     */
    public static void viewReport(JasperPrint jasperPrint, boolean isModal)
            throws JRException {
        DgReportViewer jasperViewer = new DgReportViewer(jasperPrint, isModal);
        jasperViewer.setVisible(true);
    }

    private void removeJRSaveContributor() {
        // -------net.sf.jasperreports.view.save.JRPrintSaveContributor
        // -------net.sf.jasperreports.view.save.JRPdfSaveContributor
        // -------net.sf.jasperreports.view.save.JRRtfSaveContributor
        // -------net.sf.jasperreports.view.save.JRHtmlSaveContributor
        // -------net.sf.jasperreports.view.save.JRSingleSheetXlsSaveContributor
        // -------net.sf.jasperreports.view.save.JRMultipleSheetsXlsSaveContributor
        // -------net.sf.jasperreports.view.save.JRCsvSaveContributor
        // -------net.sf.jasperreports.view.save.JRXmlSaveContributor
        // -------net.sf.jasperreports.view.save.JREmbeddedImagesXmlSaveContributor
        List<String> list = new ArrayList<String>();
        list.add(net.sf.jasperreports.view.save.JRHtmlSaveContributor.class
                .getName());
        list.add(net.sf.jasperreports.view.save.JRCsvSaveContributor.class
                .getName());
        list.add(net.sf.jasperreports.view.save.JRXmlSaveContributor.class
                .getName());
        list
                .add(net.sf.jasperreports.view.save.JREmbeddedImagesXmlSaveContributor.class
                        .getName());
        for (JRSaveContributor save : viewer.getSaveContributors()) {
            if (list.contains(save.getClass().getName())) {
                viewer.removeSaveContributor(save);
            }
        }
    }

}
package com.bestway.bcus.client.common;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

import javax.swing.text.NumberFormatter;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRField;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class CustomReportDataSource extends JREmptyDataSource  {
    private List list  = null;

    private int  index = -1;
    
    private Integer maximumFractionDigits = 6;
    
    
    
    public CustomReportDataSource(List list) {
        this.list = list;        
    }

    
    public CustomReportDataSource(List list,Integer maximumFractionDigits) {
        this.list = list;        
        this.maximumFractionDigits = maximumFractionDigits==null?0:maximumFractionDigits;
    }
    
    
    /**
     * has next data record
     */
    public boolean next()  {
        index++;
        return (index < list.size());
    }
    
    public void setFirst() {
        index = -1;
    }

    public Object getFieldValue(JRField field) {
        String fieldDescription = field.getDescription();
        try {

            Object value = PropertyUtils.getNestedProperty(list.get(index),
                    fieldDescription);
            if (value == null) {
                return "";
            }

            if (value instanceof Date) {
                java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat(
                        "yyyy-MM-dd");
                return dateFormat.format((Date) value);

            } else if (value instanceof Double || value instanceof Float) {
                Double valuesD = Double.valueOf(value.toString());
                return doubleToStr(valuesD);
            }
            return ConvertUtils.convert(value);
        } catch (Exception ex) {
            // ex.printStackTrace();
            return "";
        }
    }

    //
    // 设置小数位为6位
    //
    private NumberFormatter numberFormatter = null;

    private NumberFormatter getNumberFormatter() {
        if (numberFormatter == null) {
            numberFormatter = new NumberFormatter();
            DecimalFormat decimalFormat1 = new DecimalFormat();
            decimalFormat1.setMaximumFractionDigits(maximumFractionDigits);
            decimalFormat1.setGroupingSize(0);
            numberFormatter.setFormat(decimalFormat1);
        }
        return numberFormatter;
    }

    private String doubleToStr(Double value) { // 转换doubleToStr 取数据
        try {
            if (value == null) {
                return null;
            }
            if (value.doubleValue() == 0) {
                return "0.0";
            }
            getNumberFormatter().setValueClass(Double.class);
            //
            // 无穷大,NaN 都清0
            //
            if (value.equals(Double.NEGATIVE_INFINITY)                    
                    || value.equals(Double.POSITIVE_INFINITY)
                    || value.equals(Double.NaN)) {
                return "0.0";
            }
            return getNumberFormatter().valueToString(value);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public Integer getMaximumFractionDigits() {
        return maximumFractionDigits;
    }

    public void setMaximumFractionDigits(Integer maximumFractionDigits) {
        this.maximumFractionDigits = maximumFractionDigits;
    }
}

 

转载于:https://www.cnblogs.com/keweizhi/p/3402066.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值