Birt动态填充DataSet数据

阅读更多
看了很久的api才发现...汗死..

主要用处是结合程序来填充数据
一般做法是用ScriptDataSet,然后在报表的脚本里面调用外部class取数据.但是总感觉不爽...调试不方便.

于是如下,只要继承该类,覆盖fillDataList方法以提供自己的数据.
并在birt里面设置某个dataset的事件处理函数类为该类

ps:报表必须定义2个参数:
1.conditions,String类型,即查询参数,格式paramName1=value1¶mName2=value2
2.isDesign,Boolean类型,是否设计阶段,用来在Birt设计器里面预览用

package com.symbol.elvisapp.report;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.birt.report.engine.api.script.IColumnMetaData;
import org.eclipse.birt.report.engine.api.script.IDataSetRow;
import org.eclipse.birt.report.engine.api.script.IReportContext;
import org.eclipse.birt.report.engine.api.script.IScriptedDataSetMetaData;
import org.eclipse.birt.report.engine.api.script.IUpdatableDataSetRow;
import org.eclipse.birt.report.engine.api.script.ScriptException;
import org.eclipse.birt.report.engine.api.script.eventhandler.IScriptedDataSetEventHandler;
import org.eclipse.birt.report.engine.api.script.instance.IDataSetInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Birt DataSet的回调函数,用来给dataset赋值.
 * 关键的方法:
 * 1.beforeOpen   用来获取参数
 * 2.open         用来调用数据集取值
 * 3.fetch        用来填充数据,该函数会一直被调用直到返回false
 * 4.close        用来释放资源,记得把open里面缓存的数据引用置为null
 * 5.describe     用来动态改变dataset的meta,在open之前调用
 * 6.fillDataList 用来填充数据集,一般子类只需要覆盖该类即可使用.
 */
public class BaseDataSetEventHandler implements IScriptedDataSetEventHandler {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    public static String Key_ReportConditions = "conditions";
    public static String Key_IsDesign = "isDesign";
    public static String Regex_Conditions_Valid = "([^=]+=[^&]*(?:&?))*";
    public static String Regex_Conditions_Parse = "([^=]+)=([^&]*)(?:&?)";

    /**
     * 报表参数
     * 格式为 paramName1=value1¶mName2=value2
     */
    protected String conditions = "";

    /**
     * 解析后的报表参数
     */
    protected Map conditionMap = new HashMap();

    /**
     * 是否是设计阶段
     */
    protected boolean isDesign = false;

    /**
     * DataSet的Meta对象,用来读取列名
     */
    protected IColumnMetaData meta = null;

    /**
     * DataSet的列数
     */
    protected int metaCount = 0;

    /**
     * 数据对象列表
     */
    protected List> dataList = new ArrayList>();
    /**
     * 变量数据对象
     */
    protected Iterator> it = null;

    @Override
    public void beforeOpen(IDataSetInstance dataSet, IReportContext reportContext) throws ScriptException {
        try {
            conditions = (String) reportContext.getParameterValue(Key_ReportConditions);
            //解析参数
            if (validateConditions(conditions)) {
                parseConditions(conditions);
            }
            isDesign = Boolean.parseBoolean(String.valueOf(reportContext.getParameterValue(Key_IsDesign)));
        } catch (Exception e) {
            logger.error("获取报表参数错误(beforeOpen),Msg:{}", e);
        }
    }

    /**
     * 验证报表参数的格式是否符合格式:paramName1=value1¶mName2=value2
     */
    public boolean validateConditions(String str) {
        boolean result = Pattern.matches(Regex_Conditions_Valid, str);
        logger.debug("参数{}规则,Obj:{}", result ? "符合" : "不符合", str);
        return result;
    }

    /**
     * 把报表参数解析成map
     */
    public void parseConditions(String str) {
        Matcher m = Pattern.compile(Regex_Conditions_Parse).matcher(str);
        while (m.find()) {
            conditionMap.put(m.group(1), m.group(2));
        }
        logger.debug("成功解析参数(beforeOpen),Obj:{}", conditionMap);
    }

    /**
     * 覆盖来实现数据列表的填充
     * 一般是通过SpringUtils.getBean()得到数据提供者,如dataProvider = SpringContextUtil.getBean("beanname");
     * 然后调用list = dataProvider.getSomeDataList(conditions)传递参数去统计,然后dataList.addAll(list);
     */
    protected void fillDataList() {
    }

    /**
     * 填充测试数据
     */
    protected void fillTestData() {
        for (int i = 0; i < 5; i++) {
            Map map = new HashMap();
            try {
                for (int j = 0; j < metaCount; j++) {
                    String colName = meta.getColumnName(j + 1);
                    String colData = "ColName:" + colName + ",RowIndex:" + i + ",Conditions:" + conditions;
                    map.put(colName, colData);
                }
            } catch (ScriptException e) {
                e.printStackTrace();
            }
            dataList.add(map);
        }
    }

    @Override
    public void open(IDataSetInstance dataSet) throws ScriptException {
        try {
            meta = dataSet.getColumnMetaData();
            metaCount = meta.getColumnCount();
            //填充数据
            if (isDesign) {
                this.fillTestData();
            } else {
                this.fillDataList();
            }
            it = dataList.iterator();
        } catch (Exception e) {
            logger.error("获取报表初始化错误(Open),Msg:{}", e);
        }
    }

    @Override
    public boolean fetch(IDataSetInstance dataSet, IUpdatableDataSetRow row) throws ScriptException {
        if (it == null || !it.hasNext()) {
            return false;
        } else {
            try {
                Map data = it.next();
                //遍历meta,填值
                for (int i = 0; i < metaCount; i++) {
                    String colName = meta.getColumnName(i + 1);
                    String colData = data.get(colName);
                    row.setColumnValue(colName, colData);
                }
            } catch (ScriptException e) {
                logger.error("获取报表数据错误(fetch),Msg:{}", e);
            }
            return true;
        }
    }

    @Override
    public void close(IDataSetInstance dataSet) throws ScriptException {
        meta = null;
        dataList = null;
        it = null;
        conditionMap = null;
    }

    @Override
    public boolean describe(IDataSetInstance dataSet, IScriptedDataSetMetaData metaData) throws ScriptException {
        //用来动态改变dataset的meta,在open之前调用
        return false;
    }

    @Override
    public void onFetch(IDataSetInstance dataSet, IDataSetRow row, IReportContext reportContext) throws ScriptException {
    }

    @Override
    public void afterOpen(IDataSetInstance dataSet, IReportContext reportContext) throws ScriptException {
    }

    @Override
    public void beforeClose(IDataSetInstance dataSet, IReportContext reportContext) throws ScriptException {

    }

    @Override
    public void afterClose(IReportContext reportContext) throws ScriptException {
    }
}

你可能感兴趣的:(Eclipse,J#,脚本)