欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jasperreports自定义数据源

程序员文章站 2022-06-07 18:00:21
...

使用的是jasperreports-5.6.0版本的包。


需求:  报表由一个基本Basic对象和一个集合类CustomList对象组成

问题:jasperreports没有提供类似可用的datasource类

解决方法:自定义一个DataSource实现JRDataSource接口即可

仿照JRBeanCollectionDataSource写了一个ReportDataSource,同样使其继承JRAbstractBeanDataSource,代码如下:

public class ReportDataSource extends JRAbstractBeanDataSource {
    /**
     *
     */
    private Collection<?> data;
    private Iterator<?> iterator;
    private Object currentBean;

    private Object basicData;//基本数据

    /**
     *
     */
    public ReportDataSource(Object basicData,Collection<?> beanCollection)
    {
        this(basicData,beanCollection, true);
    }
    /**
     *
     */
    public ReportDataSource(Object basicData,Collection<?> beanCollection, boolean isUseFieldDescription)
    {
        super(isUseFieldDescription);

        this.basicData = basicData;
        this.data = beanCollection;

        if (this.data != null)
        {
            this.iterator = this.data.iterator();
        }
    }


    /**
     *
     */
    public boolean next()
    {
        boolean hasNext = false;

        if (this.iterator != null)
        {
            hasNext = this.iterator.hasNext();

            if (hasNext)
            {
                this.currentBean = this.iterator.next();
            }
        }

        return hasNext;
    }


    /**
     *
     */
    public Object getFieldValue(JRField field) throws JRException
    {
        if(field.getName().contains("basic.")){
            return getBeanProperty(basicData,field.getName().split("\\.")[1]);
        }
        return getFieldValue(currentBean, field);
    }


    /**
     *
     */
    public void moveFirst()
    {
        if (this.data != null)
        {
            this.iterator = this.data.iterator();
        }
    }

    /**
     * Returns the underlying bean collection used by this data source.
     *
     * @return the underlying bean collection
     */
    public Collection<?> getData()
    {
        return data;
    }

    /**
     * Returns the total number of records/beans that this data source
     * contains.
     *
     * @return the total number of records of this data source
     */
    public int getRecordCount()
    {
        return data == null ? 0 : data.size();
    }

    /**
     * Clones this data source by creating a new instance that reuses the same
     * underlying bean collection.
     *
     * @return a clone of this data source
     */
    public ReportDataSource cloneDataSource()
    {
        return new ReportDataSource(basicData,data);
    }
上面代码是修改JRBeanCollectionDataSource的,仅仅变动了几行代码而已,在jrmxl文件中就可以使用basic.属性名来标识Basic对象的属性了。


值得注意的是,如果CustomList为空,则无法输出报表,如果需要,可以在ReportDataSource构造器中增加  判断集合是否为空的代码,如果为空则初始化其长度为1的集合