jasperreports自定義數據源

使用的是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的集合

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章