第十三章 BIRT报表引擎API及报表API (续2)-利用BIRT设计引擎API生成报表

13.3 利用BIRT设计引擎API生成报表

前面我们在讲解BIRT报表工作模式的时候实现过一个简单的利用BIRT设计引擎API生成报表,在这一节我们详细讲解实现过程。

BIRT报表的设计引擎API是BIRT报表的核心,不论是任何形式的BIRT设计器(eclipse插件,osgi独立,standalone)还是任何形式的BIRT展示器(web viewer,用户自定义servlet viewer,rcp)都必须包含BIRT设计引擎。

BIRT design API包含如下包和类:

[html]  view plain copy
  1. Packages   
  2. org.eclipse.birt.report.model.api   
  3. org.eclipse.birt.report.model.api.activity   
  4. org.eclipse.birt.report.model.api.command   
  5. org.eclipse.birt.report.model.api.core   
  6. org.eclipse.birt.report.model.api.css   
  7. org.eclipse.birt.report.model.api.elements   
  8. org.eclipse.birt.report.model.api.elements.structures   
  9. org.eclipse.birt.report.model.api.elements.table   
  10. org.eclipse.birt.report.model.api.extension   
  11. org.eclipse.birt.report.model.api.impl   
  12. org.eclipse.birt.report.model.api.metadata   
  13. org.eclipse.birt.report.model.api.olap   
  14. org.eclipse.birt.report.model.api.scripts   
  15. org.eclipse.birt.report.model.api.simpleapi   
  16. org.eclipse.birt.report.model.api.util   
  17. org.eclipse.birt.report.model.api.validators   

用户在用java设计BIRT报表的时候都会或多或少的用到其中的4到5个包;

我们先看一个简单的例子:

[java]  view plain copy
  1. package birt;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;   
  5. import java.util.List;  
  6.   
  7. import org.eclipse.birt.core.framework.Platform;  
  8. import org.eclipse.birt.report.model.api.CellHandle;  
  9. import org.eclipse.birt.report.model.api.DataItemHandle;  
  10. import org.eclipse.birt.report.model.api.DesignConfig;   
  11. import org.eclipse.birt.report.model.api.ElementFactory;  
  12. import org.eclipse.birt.report.model.api.IDesignEngine;  
  13. import org.eclipse.birt.report.model.api.IDesignEngineFactory;  
  14. import org.eclipse.birt.report.model.api.LabelHandle;  
  15. import org.eclipse.birt.report.model.api.OdaDataSetHandle;  
  16. import org.eclipse.birt.report.model.api.OdaDataSourceHandle;  
  17. import org.eclipse.birt.report.model.api.PropertyHandle;  
  18. import org.eclipse.birt.report.model.api.ReportDesignHandle;  
  19. import org.eclipse.birt.report.model.api.RowHandle;  
  20. import org.eclipse.birt.report.model.api.SessionHandle;  
  21. import org.eclipse.birt.report.model.api.StructureFactory;  
  22. import org.eclipse.birt.report.model.api.TableHandle;  
  23. import org.eclipse.birt.report.model.api.activity.SemanticException;  
  24. import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;  
  25.   
  26. import com.ibm.icu.util.ULocale;  
  27.   
  28. /** 
  29.  * Dynamic Table BIRT Design Engine API (DEAPI) demo. 
  30.  */  
  31.   
  32. public class DECreateDynamicTable {   
  33.   
  34.    ReportDesignHandle designHandle = null;  
  35.    ElementFactory designFactory = null;  
  36.    StructureFactory structFactory = null;     
  37.    
  38.    public static void main( String[] args )  
  39.    {  
  40.        try  
  41.        {  
  42.            DECreateDynamicTable de = new DECreateDynamicTable();  
  43.            List al = new ArrayList();  
  44.            al.add("OFFICECODE");  
  45.            al.add("CITY");  
  46.            al.add("COUNTRY");  
  47.            de.buildReport(al, "From Offices" );  
  48.        }  
  49.        catch( IOException e )  
  50.        {  
  51.            e.printStackTrace();  
  52.        }  
  53.        catch( SemanticException e )  
  54.        {  
  55.            e.printStackTrace();  
  56.        }  
  57.    }  
  58.   
  59.    void buildDataSource( ) throws SemanticException  
  60.    {  
  61.        OdaDataSourceHandle dsHandle = designFactory.newOdaDataSource( "Data Source""org.eclipse.birt.report.data.oda.jdbc" );  
  62.        dsHandle.setProperty( "odaDriverClass","org.eclipse.birt.report.data.oda.sampledb.Driver" );  
  63.        dsHandle.setProperty( "odaURL""jdbc:classicmodels:sampledb" );  
  64.        dsHandle.setProperty( "odaUser""ClassicModels" );  
  65.        dsHandle.setProperty( "odaPassword""" );  
  66.   
  67.        designHandle.getDataSources( ).add( dsHandle );  
  68.    }  
  69.   
  70.    void buildDataSet(List al, String fromClause ) throws SemanticException  
  71.    {  
  72.        OdaDataSetHandle dsHandle = designFactory.newOdaDataSet( "ds","org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet" );  
  73.        dsHandle.setDataSource( "Data Source" );  
  74.        String qry = "Select ";  
  75.        forint i=0; i < al.size(); i++)  
  76.        {  
  77.            qry += " " + al.get(i);  
  78.            if( i != (al.size() -1) )  
  79.            {  
  80.                qry += ",";  
  81.            }          
  82.        }  
  83.        qry += " " + fromClause;       
  84.        dsHandle.setQueryText( qry );  
  85.       
  86.        designHandle.getDataSets( ).add( dsHandle );   
  87.    }  
  88.       
  89.    void buildReport(List al, String fromClause ) throws IOException, SemanticException  
  90.    {  
  91.        //Configure the Engine and start the Platform  
  92.        DesignConfig config = new DesignConfig( );  
  93.   
  94.        config.setProperty("BIRT_HOME""E:\\birt汉化包\\birt-runtime-3_7_2\\ReportEngine");  
  95.        IDesignEngine engine = null;  
  96.        try  
  97.        {  
  98.            Platform.startup( config );  
  99.            IDesignEngineFactory factory = (IDesignEngineFactory) Platform.createFactoryObject( IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY );  
  100.            engine = factory.createDesignEngine( config );  
  101.        }  
  102.        catch( Exception ex )  
  103.        {  
  104.            ex.printStackTrace();  
  105.        }          
  106.        SessionHandle session = engine.newSessionHandle( ULocale.ENGLISH ) ;  
  107.        try  
  108.        {  
  109.            //open a design or a template  
  110.            designHandle = session.openDesign("d:\\sample.rptdesign");  
  111.   
  112.            designFactory = designHandle.getElementFactory( );  
  113.    
  114.            buildDataSource();  
  115.            buildDataSet(al, fromClause);  
  116.    
  117.            TableHandle table = designFactory.newTableItem( "table", al.size() );  
  118.            table.setWidth( "100%" );  
  119.            table.setDataSet( designHandle.findDataSet( "ds" ) );  
  120.            PropertyHandle computedSet = table.getColumnBindings( );   
  121.            ComputedColumn  cs1 = null;  
  122.            forint i=0; i < al.size(); i++)  
  123.            {  
  124.                cs1 = StructureFactory.createComputedColumn();  
  125.                cs1.setName((String)al.get(i));  
  126.                cs1.setExpression("dataSetRow[\"" + (String)al.get(i) + "\"]");  
  127.                computedSet.addItem(cs1);  
  128.            }  
  129.            // table header  
  130.            RowHandle tableheader = (RowHandle) table.getHeader( ).get( 0 );  
  131.            forint i=0; i < al.size(); i++ )  
  132.            {  
  133.                LabelHandle label1 = designFactory.newLabel( (String)al.get(i) );      
  134.                label1.setText((String)al.get(i));  
  135.                CellHandle cell = (CellHandle) tableheader.getCells( ).get( i );  
  136.                cell.getContent( ).add( label1 );  
  137.            }                              
  138.       
  139.            // table detail  
  140.            RowHandle tabledetail = (RowHandle) table.getDetail( ).get( 0 );  
  141.            forint i=0; i < al.size(); i++ )  
  142.            {  
  143.                CellHandle cell = (CellHandle) tabledetail.getCells( ).get( i );  
  144.                DataItemHandle data = designFactory.newDataItem( "data_"+(String)al.get(i) );  
  145.                data.setResultSetColumn( (String)al.get(i));  
  146.                cell.getContent( ).add( data );  
  147.            }  
  148.    
  149.            designHandle.getBody( ).add( table );  
  150.    
  151.            // Save the design and close it.   
  152.            designHandle.saveAs( "d:\\sample3.rptdesign" ); //$NON-NLS-1$  
  153.            designHandle.close( );  
  154.            System.out.println("Finished");  
  155.        }  
  156.        catch (Exception e)  
  157.        {  
  158.            e.printStackTrace();  
  159.        }          
  160.     }  
  161.  }  

这个例子一共有四个函数 : 
1 . Main 函数: 这个例子简单之处在与它可以直接的运行,只要你修改了 
config.setProperty("BIRT_HOME", "E:\\birt汉化包\\birt-runtime-3_7_2\\ReportEngine"); 指向你自己的Birt Runtime 解压后的ReportEngine 目录. 
designHandle = session.openDesign("d:\\sample.rptdesign"); 你可以从Birt 里面建立一个新的Report template.然后指向这个report 就可以了 
designHandle.saveAs( "d:\\sample3.rptdesign" ); //$NON-NLS-1$ 指定一个你想保存的位置,c:/temp 目录存在你才能够保存到c:/temp 目录下. 
2 . buildDataSource 函数把一个ReportDesignHandle 的 Data Source 初始化, setProperties 左边的String 是不能变的,Data Source 的名字可以随便取,取DataSet 的时候要根据这个名字来取. 
3 . buildDataSet 通过拼sql 的方式 ,来build DataSet, 注意sql 别拼错了. 
4 . buildReport 注意element 的初始化顺序.在所有的DataItem 外面都是一层Cell,Cell 外面才是row .这个例子使用的row 来拼成table 的,也可以用column 来拼,相对应的数据处理也是一个column 一个 column 的处理的了

这个程序打开了一个名为sample的BIRT设计文件,往其中插入了一个1行3列的网格,列名分别为OFFICECODE,CITY,COUNTRY,没有做任何美化,另存为sample3.rptdesign

我们看看改变,sample.rptdesign预览如下:

sample3.rptdesign预览如下:

第十三章 BIRT报表引擎API及报表API (续2)-利用BIRT设计引擎API生成报表_第1张图片

这种修改不仅能表现在设计阶段,我们在调用报表引擎进行展示的时候同样可以修改,源码如下:

[java]  view plain copy
  1. package birt;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.logging.Level;   
  6.   
  7. import org.eclipse.birt.core.framework.Platform;  
  8. import org.eclipse.birt.report.engine.api.EngineConfig;  
  9. import org.eclipse.birt.report.engine.api.EngineConstants;  
  10. import org.eclipse.birt.report.engine.api.EngineException;  
  11. import org.eclipse.birt.report.engine.api.HTMLActionHandler;  
  12. import org.eclipse.birt.report.engine.api.HTMLEmitterConfig;  
  13. import org.eclipse.birt.report.engine.api.HTMLRenderContext;  
  14. import org.eclipse.birt.report.engine.api.HTMLRenderOption;  
  15. import org.eclipse.birt.report.engine.api.HTMLServerImageHandler;  
  16. import org.eclipse.birt.report.engine.api.IReportEngine;  
  17. import org.eclipse.birt.report.engine.api.IReportEngineFactory;  
  18. import org.eclipse.birt.report.engine.api.IReportRunnable;  
  19. import org.eclipse.birt.report.engine.api.IRunAndRenderTask;  
  20. import org.eclipse.birt.report.model.api.CellHandle;  
  21. import org.eclipse.birt.report.model.api.DataItemHandle;  
  22. import org.eclipse.birt.report.model.api.ElementFactory;  
  23. import org.eclipse.birt.report.model.api.LabelHandle;  
  24. import org.eclipse.birt.report.model.api.OdaDataSetHandle;  
  25. import org.eclipse.birt.report.model.api.OdaDataSourceHandle;  
  26. import org.eclipse.birt.report.model.api.PropertyHandle;  
  27. import org.eclipse.birt.report.model.api.ReportDesignHandle;  
  28. import org.eclipse.birt.report.model.api.RowHandle;  
  29. import org.eclipse.birt.report.model.api.StructureFactory;  
  30. import org.eclipse.birt.report.model.api.TableHandle;  
  31. import org.eclipse.birt.report.model.api.activity.SemanticException;  
  32. import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;  
  33.   
  34. public class ExecuteModifedReport {   
  35.   
  36.    public void runReport() throws EngineException  
  37.    {  
  38.        IReportEngine engine=null;  
  39.        EngineConfig config = null;  
  40.               
  41.        try  
  42.        {  
  43.            //Configure the Engine and start the Platform  
  44.            config = new EngineConfig( );  
  45.            config.setEngineHome( "E:\\birt汉化包\\birt-runtime-3_7_2\\ReportEngine" );  
  46.            config.setLogConfig(null, Level.FINE);  
  47.           
  48.            Platform.startup( config );  
  49.            IReportEngineFactory factory = (IReportEngineFactory) Platform.createFactoryObject( IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY );  
  50.            engine = factory.createReportEngine( config );  
  51.            engine.changeLogLevel( Level.WARNING );  
  52.        }  
  53.        catch( Exception ex )  
  54.        {  
  55.            ex.printStackTrace();  
  56.        }  
  57.           
  58.        //Configure the emitter to handle actions and images  
  59.        HTMLEmitterConfig emitterConfig = new HTMLEmitterConfig( );  
  60.        emitterConfig.setActionHandler( new HTMLActionHandler( ) );  
  61.        HTMLServerImageHandler imageHandler = new HTMLServerImageHandler( );  
  62.        emitterConfig.setImageHandler( imageHandler );  
  63.        config.getEmitterConfigs( ).put( "html", emitterConfig ); //$NON-NLS-1$  
  64.           
  65.        IReportRunnable design = null;  
  66.   
  67.        //Open the report design   
  68.        design = engine.openReportDesign("d:\\sample.rptdesign");   
  69.           
  70.        ReportDesignHandle report = (ReportDesignHandle) design.getDesignHandle( );  
  71.        buildReport( report );   
  72.           
  73.        //Create task to run and render the report,  
  74.        IRunAndRenderTask task = engine.createRunAndRenderTask(design);   
  75.           
  76.        //Set Render context to handle url and image locataions  
  77.        HTMLRenderContext renderContext = new HTMLRenderContext();  
  78.        //Set the Base URL for all actions  
  79.        renderContext.setBaseURL("baseurl");  
  80.        //Tell the Engine to prepend all images with this URL - Note this requires using the HTMLServerImageHandler  
  81.        renderContext.setBaseImageURL("urltoimages");  
  82.        //Tell the Engine where to write the images to  
  83.        renderContext.setImageDirectory("d:\\myimages");  
  84.        //Tell the Engine what image formats are supported.  Note you must have SVG in the string   
  85.        //to render charts in SVG.  
  86.        renderContext.setSupportedImageFormats("JPG;PNG;BMP;SVG");  
  87.        HashMap contextMap = new HashMap();  
  88.        contextMap.put( EngineConstants.APPCONTEXT_HTML_RENDER_CONTEXT, renderContext );  
  89.        task.setAppContext( contextMap );  
  90.        //Set parameters for the report  
  91.        //task.setParameterValues(parameters);  
  92.        //Alternatively set each seperately  
  93.        //task.setParameterValue("Top Count", new Integer(12));  
  94.        //task.validateParameters();  
  95.           
  96.        HTMLRenderOption options = new HTMLRenderOption();  
  97.           
  98.        //Set ouptut location  
  99.        options.setOutputFileName("d:\\output.html");  
  100.           
  101.        //Set output format  
  102.        options.setOutputFormat("html");  
  103.        task.setRenderOption(options);  
  104.           
  105.        //run the report and destroy the engine  
  106.        //Note - If the program stays resident do not shutdown the Platform or the Engine  
  107.        task.run();  
  108.        task.close();  
  109.        engine.destroy();  
  110.        Platform.shutdown();  
  111.        System.out.println("Finished");   
  112.    }      
  113.     
  114.    public void buildReport(ReportDesignHandle designHandle)  
  115.    {  
  116.        try  
  117.        {  
  118.            ElementFactory designFactory = designHandle.getElementFactory( );  
  119.            buildDataSource(designFactory, designHandle);  
  120.              
  121.            ArrayList cols = new ArrayList();  
  122.            cols.add("OFFICECODE");  
  123.            cols.add("CITY");  
  124.            cols.add("COUNTRY");  
  125.     
  126.            buildDataSet(cols, "From Offices", designFactory, designHandle);  
  127.   
  128.            TableHandle table = designFactory.newTableItem( "table", cols.size() );  
  129.            table.setWidth( "100%" );  
  130.            table.setDataSet( designHandle.findDataSet( "ds" ) );  
  131.   
  132.            PropertyHandle computedSet = table.getColumnBindings( );   
  133.            ComputedColumn  cs1 = null;  
  134.    
  135.            forint i=0; i < cols.size(); i++ )  
  136.            {  
  137.                cs1 = StructureFactory.createComputedColumn();  
  138.                cs1.setName((String)cols.get(i));   
  139.                cs1.setExpression("dataSetRow[\"" + (String)cols.get(i) + "\"]");  
  140.                computedSet.addItem(cs1);  
  141.            }  
  142.   
  143.            // table header  
  144.            RowHandle tableheader = (RowHandle) table.getHeader( ).get( 0 );  
  145.   
  146.            forint i=0; i < cols.size(); i++ )  
  147.            {  
  148.                LabelHandle label1 = designFactory.newLabel( (String)cols.get(i) );    
  149.                label1.setText((String)cols.get(i));  
  150.                CellHandle cell = (CellHandle) tableheader.getCells( ).get( i );  
  151.                cell.getContent( ).add( label1 );  
  152.            }                              
  153.   
  154.            // table detail  
  155.            RowHandle tabledetail = (RowHandle) table.getDetail( ).get( 0 );  
  156.            forint i=0; i < cols.size(); i++ )  
  157.            {  
  158.                CellHandle cell = (CellHandle) tabledetail.getCells( ).get( i );  
  159.                DataItemHandle data = designFactory.newDataItem( "data_"+(String)cols.get(i) );  
  160.                data.setResultSetColumn( (String)cols.get(i));  
  161.                cell.getContent( ).add( data );  
  162.            }  
  163.   
  164.            designHandle.getBody( ).add( table );  
  165.        }  
  166.        catch(Exception e)  
  167.        {  
  168.            e.printStackTrace();  
  169.        }  
  170.    }  
  171.     
  172.    void buildDataSource( ElementFactory designFactory, ReportDesignHandle designHandle ) throws SemanticException  
  173.    {  
  174.        OdaDataSourceHandle dsHandle = designFactory.newOdaDataSource( "Data Source""org.eclipse.birt.report.data.oda.jdbc" );  
  175.        dsHandle.setProperty( "odaDriverClass""org.eclipse.birt.report.data.oda.sampledb.Driver" );  
  176.        dsHandle.setProperty( "odaURL""jdbc:classicmodels:sampledb" );  
  177.        dsHandle.setProperty( "odaUser""ClassicModels" );  
  178.        dsHandle.setProperty( "odaPassword""" );  
  179.   
  180.        designHandle.getDataSources( ).add( dsHandle );  
  181.    }  
  182.   
  183.    void buildDataSet(ArrayList cols, String fromClause, ElementFactory designFactory, ReportDesignHandle designHandle ) throws SemanticException  
  184.    {  
  185.        OdaDataSetHandle dsHandle = designFactory.newOdaDataSet( "ds""org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet" );  
  186.        dsHandle.setDataSource( "Data Source" );  
  187.        String qry = "Select ";  
  188.        forint i=0; i < cols.size(); i++ )  
  189.        {  
  190.            qry += " " + cols.get(i);  
  191.            if( i != (cols.size() -1) )  
  192.            {  
  193.                qry += ",";  
  194.            }  
  195.        }  
  196.        qry += " " + fromClause;  
  197.        dsHandle.setQueryText( qry );  
  198.         designHandle.getDataSets( ).add( dsHandle );  
  199.     }  
  200.   
  201.    /** 
  202.       * @param args 
  203.       */  
  204.    public static void main(String[] args)   
  205.    {  
  206.        try  
  207.        {  
  208.            ExecuteModifedReport ex = new ExecuteModifedReport( );  
  209.            ex.runReport();  
  210.        }  
  211.        catch ( Exception e )  
  212.        {  
  213.            e.printStackTrace();  
  214.        }  
  215.    }  
  216. }  

产生的output.html内容如下:

第十三章 BIRT报表引擎API及报表API (续2)-利用BIRT设计引擎API生成报表_第2张图片

为什么能在运行展示报表之前进行设计上的修改,这是由报表展示器的设计架构决定的,前面提过,BIRT的展示器是包含了BIRT 设计引擎的,主要是在产生报表引擎阶段,如下图所示:

BIRT设计引擎API包含了报表设计所有元素的handle类,其中最重要的一些handle类结构如下:

[html]  view plain copy
  1. org.eclipse.birt.report.model.api.DesignElementHandle (implements org.eclipse.birt.report.model.elements.interfaces.IDesignElementModel)   
  2. org.eclipse.birt.report.model.api.AccessControlHandle (implements org.eclipse.birt.report.model.elements.interfaces.IAccessControlModel)   
  3. org.eclipse.birt.report.model.api.ValueAccessControlHandle (implements org.eclipse.birt.report.model.elements.interfaces.IValueAccessControlModel)   
  4. org.eclipse.birt.report.model.api.FilterConditionElementHandle (implements org.eclipse.birt.report.model.elements.interfaces.IFilterConditionElementModel)   
  5. org.eclipse.birt.report.model.api.MemberValueHandle (implements org.eclipse.birt.report.model.elements.interfaces.IMemberValueModel)   
  6. org.eclipse.birt.report.model.api.ModuleHandle (implements org.eclipse.birt.report.model.api.core.IModuleModel)   
  7. org.eclipse.birt.report.model.api.LibraryHandle (implements org.eclipse.birt.report.model.elements.interfaces.ILibraryModel)   
  8. org.eclipse.birt.report.model.api.ReportDesignHandle (implements org.eclipse.birt.report.model.elements.interfaces.IReportDesignModel)   
  9. org.eclipse.birt.report.model.api.MultiViewsHandle (implements org.eclipse.birt.report.model.elements.interfaces.IMultiViewsModel)   
  10. org.eclipse.birt.report.model.api.ReportElementHandle  
  11. org.eclipse.birt.report.model.api.CellHandle (implements org.eclipse.birt.report.model.elements.interfaces.ICellModel)   
  12. org.eclipse.birt.report.model.api.ColumnHandle (implements org.eclipse.birt.report.model.elements.interfaces.ITableColumnModel)   
  13. org.eclipse.birt.report.model.api.olap.CubeHandle (implements org.eclipse.birt.report.model.elements.interfaces.ICubeModel)   
  14. org.eclipse.birt.report.model.api.olap.OdaCubeHandle (implements org.eclipse.birt.report.model.elements.interfaces.IOdaOlapElementModel)   
  15. org.eclipse.birt.report.model.api.olap.TabularCubeHandle (implements org.eclipse.birt.report.model.elements.interfaces.ITabularCubeModel)   
  16. org.eclipse.birt.report.model.api.DataSetHandle (implements org.eclipse.birt.report.model.elements.interfaces.IDataSetModel, org.eclipse.birt.report.model.elements.interfaces.ISimpleDataSetModel)   
  17. org.eclipse.birt.report.model.api.JointDataSetHandle (implements org.eclipse.birt.report.model.elements.interfaces.IJointDataSetModel)   
  18. org.eclipse.birt.report.model.api.OdaDataSetHandle (implements org.eclipse.birt.report.model.elements.interfaces.IOdaDataSetModel)   
  19. org.eclipse.birt.report.model.api.ScriptDataSetHandle (implements org.eclipse.birt.report.model.elements.interfaces.IScriptDataSetModel)   
  20. org.eclipse.birt.report.model.api.DataSourceHandle (implements org.eclipse.birt.report.model.elements.interfaces.IDataSourceModel)   
  21. org.eclipse.birt.report.model.api.OdaDataSourceHandle (implements org.eclipse.birt.report.model.elements.interfaces.IOdaDataSourceModel, org.eclipse.birt.report.model.elements.interfaces.IOdaExtendableElementModel)   
  22. org.eclipse.birt.report.model.api.ScriptDataSourceHandle (implements org.eclipse.birt.report.model.elements.interfaces.IScriptDataSourceModel)   
  23. org.eclipse.birt.report.model.api.olap.DimensionHandle (implements org.eclipse.birt.report.model.elements.interfaces.IDimensionModel)   
  24. org.eclipse.birt.report.model.api.olap.OdaDimensionHandle (implements org.eclipse.birt.report.model.elements.interfaces.IOdaOlapElementModel)   
  25. org.eclipse.birt.report.model.api.olap.TabularDimensionHandle  
  26. org.eclipse.birt.report.model.api.GroupHandle (implements org.eclipse.birt.report.model.elements.interfaces.IGroupElementModel)   
  27. org.eclipse.birt.report.model.api.ListGroupHandle  
  28. org.eclipse.birt.report.model.api.TableGroupHandle  
  29. org.eclipse.birt.report.model.api.olap.HierarchyHandle (implements org.eclipse.birt.report.model.elements.interfaces.IHierarchyModel)   
  30. org.eclipse.birt.report.model.api.olap.OdaHierarchyHandle (implements org.eclipse.birt.report.model.elements.interfaces.IOdaOlapElementModel)   
  31. org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle (implements org.eclipse.birt.report.model.elements.interfaces.ITabularHierarchyModel)   
  32. org.eclipse.birt.report.model.api.olap.LevelHandle (implements org.eclipse.birt.report.model.elements.interfaces.ILevelModel)   
  33. org.eclipse.birt.report.model.api.olap.OdaLevelHandle  
  34. org.eclipse.birt.report.model.api.olap.TabularLevelHandle (implements org.eclipse.birt.report.model.elements.interfaces.ITabularLevelModel)   
  35. org.eclipse.birt.report.model.api.MasterPageHandle (implements org.eclipse.birt.report.model.elements.interfaces.IMasterPageModel)   
  36. org.eclipse.birt.report.model.api.GraphicMasterPageHandle (implements org.eclipse.birt.report.model.elements.interfaces.IGraphicMaterPageModel)   
  37. org.eclipse.birt.report.model.api.SimpleMasterPageHandle (implements org.eclipse.birt.report.model.elements.interfaces.ISimpleMasterPageModel)   
  38. org.eclipse.birt.report.model.api.olap.MeasureGroupHandle (implements org.eclipse.birt.report.model.elements.interfaces.IMeasureGroupModel)   
  39. org.eclipse.birt.report.model.api.olap.OdaMeasureGroupHandle  
  40. org.eclipse.birt.report.model.api.olap.TabularMeasureGroupHandle  
  41. org.eclipse.birt.report.model.api.olap.MeasureHandle (implements org.eclipse.birt.report.model.elements.interfaces.IMeasureModel)   
  42. org.eclipse.birt.report.model.api.olap.OdaMeasureHandle  
  43. org.eclipse.birt.report.model.api.olap.TabularMeasureHandle  
  44. org.eclipse.birt.report.model.api.ParameterGroupHandle (implements org.eclipse.birt.report.model.elements.interfaces.IParameterGroupModel)   
  45. org.eclipse.birt.report.model.api.CascadingParameterGroupHandle (implements org.eclipse.birt.report.model.elements.interfaces.ICascadingParameterGroupModel)   
  46. org.eclipse.birt.report.model.api.ParameterHandle (implements org.eclipse.birt.report.model.elements.interfaces.IParameterModel)   
  47. org.eclipse.birt.report.model.api.ScalarParameterHandle (implements org.eclipse.birt.report.model.elements.interfaces.IScalarParameterModel)   
  48. org.eclipse.birt.report.model.api.ReportItemHandle (implements org.eclipse.birt.report.model.api.elements.IReportItemMethodContext, org.eclipse.birt.report.model.elements.interfaces.IReportItemModel, org.eclipse.birt.report.model.elements.interfaces.IStyledElementModel)   
  49. org.eclipse.birt.report.model.api.AutoTextHandle (implements org.eclipse.birt.report.model.elements.interfaces.IAutoTextModel)   
  50. org.eclipse.birt.report.model.api.DataItemHandle (implements org.eclipse.birt.report.model.elements.interfaces.IDataItemModel)   
  51. org.eclipse.birt.report.model.api.ExtendedItemHandle (implements org.eclipse.birt.report.model.elements.interfaces.IExtendedItemModel, org.eclipse.birt.report.model.api.elements.IReportItemMethodContext)   
  52. org.eclipse.birt.report.model.api.FreeFormHandle (implements org.eclipse.birt.report.model.elements.interfaces.IFreeFormModel)   
  53. org.eclipse.birt.report.model.api.GridHandle (implements org.eclipse.birt.report.model.elements.interfaces.IGridItemModel)   
  54. org.eclipse.birt.report.model.api.ImageHandle (implements org.eclipse.birt.report.model.elements.interfaces.IImageItemModel)   
  55. org.eclipse.birt.report.model.api.LabelHandle (implements org.eclipse.birt.report.model.elements.interfaces.ILabelModel)   
  56. org.eclipse.birt.report.model.api.LineHandle (implements org.eclipse.birt.report.model.elements.interfaces.ILineItemModel)   
  57. org.eclipse.birt.report.model.api.ListingHandle (implements org.eclipse.birt.report.model.elements.interfaces.IListingElementModel)   
  58. org.eclipse.birt.report.model.api.ListHandle  
  59. org.eclipse.birt.report.model.api.TableHandle (implements org.eclipse.birt.report.model.elements.interfaces.ITableItemModel)   
  60. org.eclipse.birt.report.model.api.RectangleHandle  
  61. org.eclipse.birt.report.model.api.TextDataHandle (implements org.eclipse.birt.report.model.elements.interfaces.ITextDataItemModel)   
  62. org.eclipse.birt.report.model.api.MultiLineDataHandle  
  63. org.eclipse.birt.report.model.api.TextItemHandle (implements org.eclipse.birt.report.model.elements.interfaces.ITextItemModel)   
  64. org.eclipse.birt.report.model.api.RowHandle (implements org.eclipse.birt.report.model.elements.interfaces.ITableRowModel)   
  65. org.eclipse.birt.report.model.api.StyleHandle (implements org.eclipse.birt.report.model.elements.interfaces.IStyleModel)   
  66. org.eclipse.birt.report.model.api.PrivateStyleHandle  
  67. org.eclipse.birt.report.model.api.SharedStyleHandle  
  68. org.eclipse.birt.report.model.api.CssSharedStyleHandle  
  69. org.eclipse.birt.report.model.api.TemplateElementHandle  
  70. org.eclipse.birt.report.model.api.TemplateDataSetHandle  
  71. org.eclipse.birt.report.model.api.TemplateReportItemHandle  
  72. org.eclipse.birt.report.model.api.TemplateParameterDefinitionHandle (implements org.eclipse.birt.report.model.elements.interfaces.ITemplateParameterDefinitionModel)   
  73. org.eclipse.birt.report.model.api.ThemeHandle (implements org.eclipse.birt.report.model.elements.interfaces.IThemeModel)   
  74. org.eclipse.birt.report.model.api.SortElementHandle (implements org.eclipse.birt.report.model.elements.interfaces.ISortElementModel)   
  75. org.eclipse.birt.report.model.api.VariableElementHandle (implements org.eclipse.birt.report.model.elements.interfaces.IVariableElementModel)   

报表设计器本身包含所有的这些引擎类,当然也包含用于数据源,图表,展示的引擎:

第十三章 BIRT报表引擎API及报表API (续2)-利用BIRT设计引擎API生成报表_第3张图片

设计引擎中的主要类如下:

ReportDesignHandle类:

代表整个报表设计,报表设计定义了用于描述整个设计的特征,基础等等的一组属性。除了属性之外,报表设计也包含一些组成报表的元素。

这些元素包括:

Code Modules,适用于整个设计的全局脚本

Parameters,一个用于描述用户在运行报表时输入的数据参数元素的集合(list

Data Sources,报表使用的数据源

Data Sets,报表定义的数据集

Color Palette,一个自定义的颜色名称的集合(set),并且是报表的一部分

Styles,用户在报表中自定义的用于格式化元素的样式文件,在这个样式文件的集合中,每种样式必须有唯一的名字。

Page Setup,代表报表内的母版页布局

Components,报表中定义的可重复使用的报表项目中。报表项目可以扩大这些项目。可以为这个设计定义了一个“私人图书馆”

Body,Visual报表的内容清单。内容是由一个或多个节组成的。一个节是一个报表项目填补了页面的宽度。它可以包含文字,表格,列表,表格等元素

Scratch Pad,当重建报表时需要提供一个临时的地方移动报表项目。

Translations,针对报表的额外的消息列表集合

Images    报表中嵌入的图像列表集合

模块允许使用在库中定义的组件

[java]  view plain copy
  1. // Include one library  
  2.                         
  3.                       ReportDesignHandle designHandle = ...;  
  4.                       designHandle.includeLibrary( "libA.rptlibrary""LibA" );  
  5.                       LibraryHandle libraryHandle = designHandle.getLibrary("LibA");  
  6.                          
  7. // Create one label based on the one in library  
  8.                        
  9.                       LabelHandle labelHandle = (LabelHandle) libraryHandle.findElement("companyNameLabel");  
  10.                       LabelHandle myLabelHandle = (LabelHandle) designHandle.getElementFactory().newElementFrom( labelHandle, "myLabel" );  
  11.                        
  12. // Add the new label into design file  
  13.                        
  14.                       designHandle.getBody().add(myLabelHandle);  

除了继承自org.eclipse.birt.report.model.api.ModuleHandle的方法,继承自org.eclipse.birt.report.model.api.DesignElementHandle的方法,LibraryHandle还有自有的方法:

ElementFactory

创建一个新的报表元素,并返回处理它。使用这个类来创建报表元素。创建一个元素后,通过SlotHandle类中的增加方法将它添加到设计中。通过调用这个类的getElementFactory方法来获取一个实例

SessionHandle

代表报表设计的状态 – 一个用户有一个session。在Eclipse环境中,这代表了开放的设计集。在网络环境中,这代表了开放设计的session和语言环境。session有一个默认的样式属性集合和默认单位。session还拥有一些方法来创建和打开的报表设计。

OdaDataSourceHandle

代表数据源

OdaDataSetHandle

代表数据集

DesignConfig

报表设计引擎配置设置。允许引擎提供图像处理,超链接处理和字体处理等个性化的实现

IdesignEngine

代表作为一个整体BIRT的设计引擎。用于创建新的会话session

IDesignEngineFactory

工厂类,用于创建一个新的设计引擎实例。

TableHandle

代表一个table元素。一个table有一个本地化的标题,并且可以重复其在每一页上的标题。一个table是一个结构化的行和列的清单集合。这些列被定义为整个表,这些行被聚集成集。

PropertyHandle

一个用于处理一个元素的顶级物业工作的处理器

ComputedColumn

描述了一个为数据集或报表查询而定义的计算列。计算列有一个名字,和一个JavaScript表达式,用于计算这个列的值

StructureFactory

提供一个工厂方法,用于创建一个空的结构

RowHandle

代表一个网格或者表格中的一行。每一行包含多个cell,每一行可以定义它的高度。

CellHandle

代表了一个表或表格里的单元格cell一个单元格cell可以跨越多行或列。一个单元格cell可以包含零个,一个或多个内容content不过,由于BIRT的多个项目将自动定位,如果单元格cell拥有多个项目应用程序一般应提供其自己的集装箱container

应用程序一般不直接创造cell处理器。相反,它使用的导航方法对其他元素提供一个处理诸如RowHandle

DataItemHandle

代表一个数据项元素。一个数据项有一个动作,值表达和帮助文本

EngineConfig

环绕的报表引擎的配置设置。允许开发人员指定在何处寻找引擎插件,数据驱动,并在写图像文件。允许用户自定义数据相关的属性(即数据引擎)。也可以让引擎提供的图像处理,超链接处理和字体处理等个性化的实现

IReportEngineFactory

一个工厂类,用于创建报表引擎。

IReportEngine

代表一个报表引擎

一个报表引擎提供了报表功能的切入点。这是全球定制的报表生成和渲染过程。这也是引擎收集统计数据的地方。通过报表引擎,报表生成,并能提供不同的输出格式。查询也可以执行预览的目的,不涉及一个完整的报告生成

HTMLRenderOption

用于输出网页格式的报表

用户可以通过查询API文档查询每个handle的用法,如何修改设计,在此我不在把API文档粘贴过来,如下:

下面的例子演示了SessionHandle,ReportDesignHandle,IncludedCssStyleSheetHandle,SlotHandle,DesignElementHandle,PropertyHandle,StructureHandle,MemberHandle,GridHandle,ListingHandle,ImageHandle,ExtendedItemHandle的用法

[java]  view plain copy
  1. package birtbird;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.Iterator;  
  5. import java.util.List;  
  6.   
  7. import org.eclipse.birt.chart.model.Chart;  
  8. import org.eclipse.birt.core.framework.Platform;  
  9. import org.eclipse.birt.report.model.api.CellHandle;  
  10. import org.eclipse.birt.report.model.api.DesignConfig;  
  11. import org.eclipse.birt.report.model.api.DesignElementHandle;  
  12. import org.eclipse.birt.report.model.api.ExtendedItemHandle;  
  13. import org.eclipse.birt.report.model.api.GridHandle;  
  14. import org.eclipse.birt.report.model.api.IDesignEngine;  
  15. import org.eclipse.birt.report.model.api.IDesignEngineFactory;  
  16. import org.eclipse.birt.report.model.api.ImageHandle;  
  17. import org.eclipse.birt.report.model.api.IncludedCssStyleSheetHandle;  
  18. import org.eclipse.birt.report.model.api.ListingHandle;  
  19. import org.eclipse.birt.report.model.api.MemberHandle;  
  20. import org.eclipse.birt.report.model.api.PropertyHandle;  
  21. import org.eclipse.birt.report.model.api.ReportDesignHandle;  
  22. import org.eclipse.birt.report.model.api.RowHandle;  
  23. import org.eclipse.birt.report.model.api.SessionHandle;  
  24. import org.eclipse.birt.report.model.api.SlotHandle;  
  25. import org.eclipse.birt.report.model.api.StructureHandle;  
  26. import org.eclipse.birt.report.model.api.activity.SemanticException;  
  27. import org.eclipse.birt.report.model.api.metadata.IStructureDefn;  
  28.   
  29. import com.ibm.icu.util.ULocale;  
  30.   
  31. public class ReportDesignDetails {  
  32.   
  33.     public static void main(String[] args) {  
  34.         try {  
  35.             buildReport();  
  36.         } catch (IOException e) {  
  37.             e.printStackTrace();  
  38.         } catch (SemanticException e) {  
  39.             e.printStackTrace();  
  40.         }  
  41.     }  
  42.   
  43.     static void buildReport() throws IOException, SemanticException {  
  44.         // Create a session handle. This is used to manage all open designs.  
  45.         // Your app need create the session only once.  
  46.         DesignConfig config = new DesignConfig();  
  47.         config.setBIRTHome("E:\\birt汉化包\\birt-runtime-3_7_2\\ReportEngine");  
  48.         IDesignEngine engine = null;  
  49.         try {  
  50.             Platform.startup(config);  
  51.             IDesignEngineFactory factory = (IDesignEngineFactory) Platform  
  52.                     .createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);  
  53.             engine = factory.createDesignEngine(config);  
  54.         } catch (Exception ex) {  
  55.             ex.printStackTrace();  
  56.         }  
  57.         SessionHandle session = engine.newSessionHandle(ULocale.ENGLISH);  
  58.         ReportDesignHandle design = null;  
  59.         try {  
  60.             design = session.openDesign("d:\\TopNPercent.rptdesign");  
  61.             List cssStyleSheets = design.getAllStyles();// getAllCssStyleSheets();  
  62.             int size = cssStyleSheets.size();  
  63.             Iterator myincludecssiter = design.includeCssesIterator();  
  64.             while (myincludecssiter.hasNext()) {  
  65.                 IncludedCssStyleSheetHandle css = (IncludedCssStyleSheetHandle) myincludecssiter  
  66.                         .next();  
  67.                 // System.out.println( css.getFileName());  
  68.   
  69.             }  
  70.             SlotHandle sh = design.getBody();  
  71.             System.out.println("Contents Count: " + sh.getCount());  
  72.             Iterator it = sh.iterator();  
  73.             while (it.hasNext()) {  
  74.                 DesignElementHandle de = (DesignElementHandle) it.next();  
  75.                 // System.out.println(de.getName());  
  76.   
  77.             }  
  78.             sh = design.getDataSources();  
  79.             it = sh.iterator();  
  80.             while (it.hasNext()) {  
  81.                 DesignElementHandle de = (DesignElementHandle) it.next();  
  82.                 // System.out.println(de.getName());  
  83.             }  
  84.             sh = design.getDataSets();  
  85.             it = sh.iterator();  
  86.             while (it.hasNext()) {  
  87.                 DesignElementHandle de = (DesignElementHandle) it.next();  
  88.                 // System.out.println(de.getName());  
  89.             }  
  90.             sh = design.getMasterPages();  
  91.             it = sh.iterator();  
  92.             while (it.hasNext()) {  
  93.                 DesignElementHandle de = (DesignElementHandle) it.next();  
  94.                 // System.out.println(de.getName());  
  95.             }  
  96.             sh = design.getParameters();  
  97.             it = sh.iterator();  
  98.             while (it.hasNext()) {  
  99.                 DesignElementHandle de = (DesignElementHandle) it.next();  
  100.                 // System.out.println(de.getName());  
  101.             }  
  102.             System.out.println("Slot Count for a report design "  
  103.                     + design.getDefn().getSlotCount());  
  104.             for (int i = 0; i < design.getDefn().getSlotCount(); i++) {  
  105.                 // System.out.println(" Slot " + i + " -- " +  
  106.                 // design.getDefn().getSlot(i).getName());  
  107.             }  
  108.             Iterator pit = design.getPropertyIterator();  
  109.             while (pit.hasNext()) {  
  110.                 PropertyHandle ph = (PropertyHandle) pit.next();  
  111.                 IStructureDefn structDefn = ph.getPropertyDefn().getStructDefn();  
  112.                 if (structDefn != null)  
  113.                 {  
  114.                     // System.out.println("ListProperty " +  
  115.                     // ph.getPropertyDefn().getDisplayName());  
  116.                     Iterator structIterator = ph.iterator();  
  117.                     while (structIterator.hasNext()) {  
  118.                         StructureHandle structHandle = (StructureHandle) structIterator.next();  
  119.                         Iterator memberIterator = structHandle.iterator();  
  120.                         while (memberIterator.hasNext())  
  121.                         {  
  122.                             MemberHandle memHandle = (MemberHandle) memberIterator.next();  
  123.                             // System.out.println( " Structure Item " +  
  124.                             // memHandle.getDefn( ).getDisplayName( ) + "---" +  
  125.                             // memHandle.getValue() );  
  126.                         }  
  127.                     }  
  128.                 } else {  
  129.   
  130.                     System.out.println("StandardProperty "  
  131.                             + ph.getPropertyDefn().getDisplayName() + "--"  
  132.                             + ph.getValue());  
  133.   
  134.                 }  
  135.             }  
  136.   
  137.             // Instantiate a slot handle and iterator for the body slot.  
  138.             SlotHandle shBody = design.getBody();  
  139.             Iterator slotIterator = shBody.iterator();  
  140.             // To retrieve top-level report items, iterate over the body.  
  141.             while (slotIterator.hasNext()) {  
  142.                 Object shContents = slotIterator.next();  
  143.                 // To get the contents of the top-level report items,  
  144.                 // instantiate slot handles.  
  145.                 if (shContents instanceof GridHandle) {  
  146.                     GridHandle grid = (GridHandle) shContents;  
  147.                     parseGrid(grid);  
  148.                 }  
  149.                 if (shContents instanceof ListingHandle) {  
  150.                     ListingHandle list = (ListingHandle) shContents;  
  151.                     parseList(list);  
  152.                 }  
  153.                 if (shContents instanceof ImageHandle) {  
  154.                     String imageSource = ((ImageHandle) shContents).getSource();  
  155.                     ImageHandle ih = (ImageHandle) shContents;  
  156.                     System.out.println(ih.getImageName());  
  157.                     // Check that the image has a URI.  
  158.                 }  
  159.                 if (shContents instanceof ExtendedItemHandle) {  
  160.                     String type = ((ExtendedItemHandle) shContents)  
  161.                             .getExtensionName();  
  162.                     if (type.compareToIgnoreCase("Crosstab") == 0) {  
  163.                         System.out.println("Found a crosstab");  
  164.                     }  
  165.                     if (type.compareToIgnoreCase("Chart") == 0) {  
  166.                         Chart cm = (Chart) ((ExtendedItemHandle) shContents)  
  167.                                 .getReportItem().getProperty("chart.instance");  
  168.                         System.out.println("Found chart of type "  
  169.                                 + cm.getType());  
  170.                     }  
  171.   
  172.                 }  
  173.             }  
  174.   
  175.             design.close();  
  176.             Platform.shutdown();  
  177.   
  178.         } catch (Exception e) {  
  179.             e.printStackTrace();  
  180.         }  
  181.         System.out.println("Finished");  
  182.   
  183.         // We're done!  
  184.     }  
  185.   
  186.     public static void parseGrid(GridHandle grid) {  
  187.         SlotHandle grRows = grid.getRows();  
  188.         Iterator rowIterator = grRows.iterator();  
  189.         parseRow(rowIterator);  
  190.     }  
  191.   
  192.     public static void parseList(ListingHandle list) {  
  193.         SlotHandle grRows = list.getHeader();  
  194.         Iterator rowIterator = grRows.iterator();  
  195.         parseRow(rowIterator);  
  196.         grRows = list.getDetail();  
  197.         rowIterator = grRows.iterator();  
  198.         parseRow(rowIterator);  
  199.         grRows = list.getFooter();  
  200.         rowIterator = grRows.iterator();  
  201.         parseRow(rowIterator);  
  202.         grRows = list.getGroups();  
  203.         rowIterator = grRows.iterator();  
  204.         parseRow(rowIterator);  
  205.     }  
  206.   
  207.     public static void parseRow(Iterator rowIterator) {  
  208.   
  209.         while (rowIterator.hasNext()) {  
  210.             // Get RowHandle objects.  
  211.             Object rowSlotContents = rowIterator.next();  
  212.             // To find the image element, iterate over the grid.  
  213.             SlotHandle cellSlot = ((RowHandle) rowSlotContents).getCells();  
  214.             Iterator cellIterator = cellSlot.iterator();  
  215.             while (cellIterator.hasNext()) {  
  216.                 // Get a CellHandle object.  
  217.                 Object cellSlotContents = cellIterator.next();  
  218.                 SlotHandle cellContentSlot = ((CellHandle) cellSlotContents)  
  219.                         .getContent();  
  220.                 Iterator cellContentIterator = cellContentSlot.iterator();  
  221.                 while (cellContentIterator.hasNext()) {  
  222.                     // Get a DesignElementHandle object.  
  223.                     Object cellContents = cellContentIterator.next();  
  224.                     // Check that the element is an image.  
  225.                     if (cellContents instanceof ImageHandle) {  
  226.                         String imageSource = ((ImageHandle) cellContents)  
  227.                                 .getSource();  
  228.                         ImageHandle ih = (ImageHandle) cellContents;  
  229.                         System.out.println(ih.getImageName());  
  230.                         // Check that the image has a URI.  
  231.   
  232.                     }  
  233.                     if (cellContents instanceof GridHandle) {  
  234.                         parseGrid((GridHandle) cellContents);  
  235.   
  236.                     }  
  237.                     if (cellContents instanceof ListingHandle) {  
  238.                         parseList((ListingHandle) cellContents);  
  239.   
  240.                     }  
  241.                     if (cellContents instanceof ExtendedItemHandle) {  
  242.                         String type = ((ExtendedItemHandle) cellContents)  
  243.                                 .getExtensionName();  
  244.                         if (type.compareToIgnoreCase("Crosstab") == 0) {  
  245.                             System.out.println("Found a crosstab");  
  246.                         }  
  247.                         if (type.compareToIgnoreCase("Chart") == 0) {  
  248.                             try {  
  249.                                 Chart cm = (Chart) ((ExtendedItemHandle) cellContents)  
  250.                                         .getReportItem().getProperty(  
  251.                                                 "chart.instance");  
  252.                                 System.out.println("Found chart of type "  
  253.                                         + cm.getType());  
  254.                             } catch (Exception e) {  
  255.                                 e.printStackTrace();  
  256.                             }  
  257.                         }  
  258.   
  259.                     }  
  260.   
  261.                 }  
  262.             }  
  263.         }  
  264.     }  
  265.   
  266. }  

上面的源码读取一个设计文档TopNPercent.rptdesign,并未进行修改,在控制台打印设计信息如下:

[html]  view plain copy
  1. Contents Count: 3  
  2. Slot Count for a report design 11  
  3. StandardProperty Refresh rate--0  
  4. StandardProperty Event handler class--null  
  5. StandardProperty New handler on each event--false  
  6. StandardProperty Layout preference--auto layout  
  7. StandardProperty Report orientation--ltr  
  8. StandardProperty Enable Data Security--false  
  9. StandardProperty Cascade ACL--true  
  10. StandardProperty ACL expression--null  
  11. StandardProperty Image DPI--null  
  12. StandardProperty Page variables--null  
  13. StandardProperty Data objects--null  
  14. StandardProperty Locale--null  
  15. StandardProperty Initialize--null  
  16. StandardProperty On prepare--null  
  17. StandardProperty Before factory--null  
  18. StandardProperty After factory--null  
  19. StandardProperty Before render--null  
  20. StandardProperty After render--null  
  21. StandardProperty On page start--null  
  22. StandardProperty On page end--null  
  23. StandardProperty Display name--null  
  24. StandardProperty Display name key--null  
  25. StandardProperty Icon file--null  
  26. StandardProperty Cheat sheet--null  
  27. StandardProperty Thumbnail--null  
  28. StandardProperty Subject--null  
  29. StandardProperty Help guide--null  
  30. StandardProperty Base--null  
  31. StandardProperty Units--in  
  32. StandardProperty Theme--null  
  33. StandardProperty Author--Mark Coggins  
  34. StandardProperty Title--Top Classic Models Inc. Customers by Revenue  
  35. StandardProperty Title key--null  
  36. StandardProperty Description--null  
  37. StandardProperty Description key--null  
  38. StandardProperty Comments--null  
  39. StandardProperty Include resource--null  
  40. StandardProperty Created by--Eclipse BIRT Designer Version 2.5.2.v20100208 Build <2.5.2.v20100210-0630>  
  41. StandardProperty External Meta Data--null  
  42. C:\Documents and Settings\pclenahan\My Documents\ClassicModels\logos\Classic-Models-Full-M.jpg  
  43. Found chart of type Bar Chart  
  44. Finished  

下面是一个综合利用各种报表元素handle生成的一个相对复杂的报表,加入了突出显示,报表参数,动态排序,聚合等等

[java]  view plain copy
  1. package birtbird;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import java.io.BufferedInputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9.   
  10. import org.eclipse.birt.core.framework.Platform;  
  11. import org.eclipse.birt.report.model.api.CellHandle;  
  12. import org.eclipse.birt.report.model.api.ColumnHandle;  
  13. import org.eclipse.birt.report.model.api.DataItemHandle;  
  14. import org.eclipse.birt.report.model.api.DesignConfig;  
  15. import org.eclipse.birt.report.model.api.ElementFactory;  
  16. import org.eclipse.birt.report.model.api.IDesignEngine;  
  17. import org.eclipse.birt.report.model.api.IDesignEngineFactory;  
  18. import org.eclipse.birt.report.model.api.LabelHandle;  
  19. import org.eclipse.birt.report.model.api.ImageHandle;  
  20. import org.eclipse.birt.report.model.api.ActionHandle;  
  21. import org.eclipse.birt.report.model.api.ReportElementHandle;  
  22. import org.eclipse.birt.report.model.api.RowOperationParameters;  
  23. import org.eclipse.birt.report.model.api.ScalarParameterHandle;  
  24. import org.eclipse.birt.report.model.api.ScriptLibHandle;  
  25. import org.eclipse.birt.report.model.api.TextItemHandle;  
  26. import org.eclipse.birt.report.model.elements.JointDataSet;  
  27.   
  28. import org.eclipse.birt.report.model.api.OdaDataSetHandle;  
  29. import org.eclipse.birt.report.model.api.JointDataSetHandle;  
  30. import org.eclipse.birt.report.model.api.JoinConditionHandle;  
  31.   
  32. import org.eclipse.birt.report.model.api.OdaDataSourceHandle;  
  33. import org.eclipse.birt.report.model.api.PropertyHandle;  
  34. import org.eclipse.birt.report.model.api.ReportDesignHandle;  
  35. import org.eclipse.birt.report.model.api.RowHandle;  
  36. import org.eclipse.birt.report.model.api.SessionHandle;  
  37. import org.eclipse.birt.report.model.api.StructureFactory;  
  38. import org.eclipse.birt.report.model.api.TableHandle;  
  39. import org.eclipse.birt.report.model.api.activity.SemanticException;  
  40. import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;  
  41. import org.eclipse.birt.report.model.api.PropertyHandle;  
  42. import org.eclipse.birt.report.model.elements.ReportItem;  
  43.   
  44. import org.eclipse.birt.report.model.api.elements.structures.EmbeddedImage;  
  45.   
  46. import org.eclipse.birt.report.model.elements.Style;  
  47. import org.eclipse.birt.report.model.elements.ReportDesign;  
  48.   
  49. import org.eclipse.birt.report.model.api.StyleHandle;  
  50.   
  51. import org.eclipse.birt.report.model.api.elements.structures.AggregationArgument;  
  52. import org.eclipse.birt.report.model.api.elements.structures.DateTimeFormatValue;  
  53. import org.eclipse.birt.report.model.api.elements.structures.FormatValue;  
  54. import org.eclipse.birt.report.model.api.elements.structures.MapRule;  
  55. import org.eclipse.birt.report.model.api.elements.structures.HideRule;  
  56. import org.eclipse.birt.report.model.api.elements.structures.PropertyBinding;  
  57. import org.eclipse.birt.report.model.api.elements.structures.TOC;  
  58. import org.eclipse.birt.report.model.api.elements.structures.JoinCondition;  
  59. import org.eclipse.birt.report.model.api.elements.structures.ParamBinding;  
  60.   
  61. import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;  
  62.   
  63. import org.eclipse.birt.report.model.api.elements.structures.HighlightRule;  
  64. import org.eclipse.birt.report.model.elements.interfaces.IJointDataSetModel;  
  65.   
  66. import org.eclipse.birt.report.model.api.elements.structures.SortKey;  
  67. import org.eclipse.birt.report.model.api.SortKeyHandle;  
  68.   
  69. import org.eclipse.birt.report.model.api.elements.structures.FilterCondition;  
  70. import org.eclipse.birt.report.model.api.elements.structures.Action;  
  71. import org.eclipse.birt.report.model.api.elements.structures.IncludeScript;  
  72. import java.util.Iterator;  
  73.   
  74. import com.ibm.icu.util.ULocale;  
  75.   
  76. /** 
  77.  * Simple BIRT Design Engine API (DEAPI) demo. 
  78.  */  
  79.   
  80. public class StructFactoryTest {  
  81.     ReportDesignHandle designHandle = null;  
  82.     ElementFactory designFactory = null;  
  83.     StructureFactory structFactory = null;  
  84.   
  85.     public static void main(String[] args) {  
  86.         try {  
  87.             StructFactoryTest de = new StructFactoryTest();  
  88.             de.buildReport();  
  89.         } catch (IOException e) {  
  90.             // TODO Auto-generated catch block  
  91.             e.printStackTrace();  
  92.         } catch (SemanticException e) {  
  93.             // TODO Auto-generated catch block  
  94.             e.printStackTrace();  
  95.         }  
  96.     }  
  97.   
  98.     void buildDataSource() throws SemanticException {  
  99.   
  100.         OdaDataSourceHandle dsHandle = designFactory.newOdaDataSource(  
  101.                 "Data Source""org.eclipse.birt.report.data.oda.jdbc");  
  102.         dsHandle.setProperty("odaDriverClass",  
  103.                 "org.eclipse.birt.report.data.oda.sampledb.Driver");  
  104.         dsHandle.setProperty("odaURL""jdbc:classicmodels:sampledb");  
  105.         dsHandle.setProperty("odaUser""ClassicModels");  
  106.         dsHandle.setProperty("odaPassword""");  
  107.   
  108.         PropertyBinding pb = new PropertyBinding();  
  109.   
  110.         designHandle.getDataSources().add(dsHandle);  
  111.         long currid = dsHandle.getID();  
  112.   
  113.     }  
  114.   
  115.     void buildDataSet() throws SemanticException {  
  116.   
  117.         OdaDataSetHandle dsHandle = designFactory.newOdaDataSet("ds",  
  118.                 "org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet");  
  119.         dsHandle.setDataSource("Data Source");  
  120.         String qry = "Select * from customers";  
  121.   
  122.         dsHandle.setQueryText(qry);  
  123.   
  124.         addFilterCondition(dsHandle);  
  125.   
  126.         designHandle.getDataSets().add(dsHandle);  
  127.   
  128.     }  
  129.   
  130.     void buildDataSet2() throws SemanticException {  
  131.   
  132.         OdaDataSetHandle dsHandle = designFactory.newOdaDataSet("ds2",  
  133.                 "org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet");  
  134.         dsHandle.setDataSource("Data Source");  
  135.         String qry = "Select * from orderdetails where ordernumber = ?";  
  136.   
  137.         dsHandle.setQueryText(qry);  
  138.   
  139.         addFilterCondition(dsHandle);  
  140.   
  141.         designHandle.getDataSets().add(dsHandle);  
  142.   
  143.     }  
  144.   
  145.     void buildJointDataSet() throws SemanticException {  
  146.         OdaDataSetHandle dsHandle1 = designFactory.newOdaDataSet("ds1",  
  147.                 "org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet");  
  148.         dsHandle1.setDataSource("Data Source");  
  149.         String qry1 = "Select * from customers";  
  150.   
  151.         dsHandle1.setQueryText(qry1);  
  152.   
  153.         OdaDataSetHandle dsHandle2 = designFactory.newOdaDataSet("ds2",  
  154.                 "org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet");  
  155.         dsHandle2.setDataSource("Data Source");  
  156.         String qry2 = "Select * from orders";  
  157.   
  158.         dsHandle2.setQueryText(qry2);  
  159.   
  160.         JointDataSetHandle jds = designFactory.newJointDataSet("test");  
  161.   
  162.         designHandle.getDataSets().add(dsHandle1);  
  163.         designHandle.getDataSets().add(dsHandle2);  
  164.   
  165.         jds.addDataSet("ds1");  
  166.         jds.addDataSet("ds2");  
  167.   
  168.         String leftExpression = "dataSetRow[\"CUSTOMERNUMBER\"]";  
  169.         String rightExpression = "dataSetRow[\"CUSTOMERNUMBER\"]";  
  170.         JoinCondition condition = StructureFactory.createJoinCondition();  
  171.         condition.setJoinType(DesignChoiceConstants.JOIN_TYPE_LEFT_OUT);  
  172.         condition.setOperator(DesignChoiceConstants.JOIN_OPERATOR_EQALS);  
  173.         condition.setLeftDataSet("ds1"); //$NON-NLS-1$  
  174.         condition.setRightDataSet("ds2"); //$NON-NLS-1$  
  175.         condition.setLeftExpression(leftExpression); //$NON-NLS-1$  
  176.         condition.setRightExpression(rightExpression); //$NON-NLS-1$  
  177.   
  178.         PropertyHandle conditionHandle = jds  
  179.                 .getPropertyHandle(JointDataSet.JOIN_CONDITONS_PROP);  
  180.         conditionHandle.addItem(condition);  
  181.   
  182.         designHandle.getDataSets().add(jds);  
  183.   
  184.     }  
  185.   
  186.     void addMapRule(TableHandle th) {  
  187.         try {  
  188.   
  189.             MapRule mr = structFactory.createMapRule();  
  190.             mr.setTestExpression("row[\"CustomerCreditLimit\"]");  
  191.             mr.setOperator(DesignChoiceConstants.MAP_OPERATOR_EQ);  
  192.             mr.setValue1("0");  
  193.             mr.setDisplay("N/A");  
  194.   
  195.             PropertyHandle ph = th  
  196.                     .getPropertyHandle(StyleHandle.MAP_RULES_PROP);  
  197.             ph.addItem(mr);  
  198.         } catch (Exception e) {  
  199.             e.printStackTrace();  
  200.         }  
  201.     }  
  202.   
  203.     void addVisRule(ReportElementHandle rh) {  
  204.         try {  
  205.             HideRule hr = structFactory.createHideRule();  
  206.             hr.setFormat("pdf");  
  207.             hr.setExpression("true");  
  208.   
  209.             PropertyHandle ph = rh  
  210.                     .getPropertyHandle(ReportItem.VISIBILITY_PROP);  
  211.             ph.addItem(hr);  
  212.         } catch (Exception e) {  
  213.             e.printStackTrace();  
  214.         }  
  215.     }  
  216.   
  217.     void addBottomBorder(ReportElementHandle rh) {  
  218.         try {  
  219.   
  220.             rh.setProperty(StyleHandle.BORDER_BOTTOM_COLOR_PROP, "#000000");  
  221.             rh.setProperty(StyleHandle.BORDER_BOTTOM_STYLE_PROP, "solid");  
  222.             rh.setProperty(StyleHandle.BORDER_BOTTOM_WIDTH_PROP, "2px");  
  223.   
  224.         } catch (Exception e) {  
  225.             e.printStackTrace();  
  226.         }  
  227.     }  
  228.   
  229.     void addHighLightRule(RowHandle th) {  
  230.         try {  
  231.             HighlightRule hr = structFactory.createHighlightRule();  
  232.   
  233.             hr.setOperator(DesignChoiceConstants.MAP_OPERATOR_GT);  
  234.             hr.setTestExpression("row[\"CustomerCreditLimit\"]");  
  235.             hr.setValue1("100000");  
  236.             hr.setProperty(HighlightRule.BACKGROUND_COLOR_MEMBER, "blue");  
  237.   
  238.             PropertyHandle ph = th  
  239.                     .getPropertyHandle(StyleHandle.HIGHLIGHT_RULES_PROP);  
  240.   
  241.             ph.addItem(hr);  
  242.         } catch (Exception e) {  
  243.             e.printStackTrace();  
  244.         }  
  245.     }  
  246.   
  247.     void addSortKey(TableHandle th) {  
  248.         try {  
  249.             SortKey sk = structFactory.createSortKey();  
  250.             // sk.setKey("row[\"CustomerName\"]");  
  251.             sk.setDirection(DesignChoiceConstants.SORT_DIRECTION_ASC);  
  252.             sk.setKey("if( params[\"srt\"].value){ if( params[\"srt\"].value == 'a' ){  row[\"CustomerName\"]; }else{ row[\"CustomerCity\"];}}");  
  253.   
  254.             PropertyHandle ph = th.getPropertyHandle(TableHandle.SORT_PROP);  
  255.             ph.addItem(sk);  
  256.         } catch (Exception e) {  
  257.             e.printStackTrace();  
  258.         }  
  259.     }  
  260.   
  261.     void modSortKey(TableHandle th) {  
  262.         try {  
  263.             SortKeyHandle sk;  
  264.             PropertyHandle ph = th.getPropertyHandle(TableHandle.SORT_PROP);  
  265.             // get number or iterate  
  266.             sk = (SortKeyHandle) ph.get(0);  
  267.             sk.setDirection(DesignChoiceConstants.SORT_DIRECTION_DESC);  
  268.         } catch (Exception e) {  
  269.             e.printStackTrace();  
  270.         }  
  271.     }  
  272.   
  273.     void addFilterCondition(OdaDataSetHandle dh) {  
  274.         try {  
  275.             FilterCondition fc = structFactory.createFilterCond();  
  276.             fc.setExpr("row[\"COUNTRY\"]");  
  277.             fc.setOperator(DesignChoiceConstants.MAP_OPERATOR_EQ);  
  278.             fc.setValue1("'USA'");  
  279.   
  280.             dh.addFilter(fc);  
  281.   
  282.         } catch (Exception e) {  
  283.             e.printStackTrace();  
  284.         }  
  285.     }  
  286.   
  287.     void addFilterCondition(TableHandle th) {  
  288.         try {  
  289.   
  290.             FilterCondition fc = structFactory.createFilterCond();  
  291.             fc.setExpr("row[\"CustomerCountry\"]");  
  292.             fc.setOperator(DesignChoiceConstants.MAP_OPERATOR_EQ);  
  293.             fc.setValue1("'USA'");  
  294.   
  295.             PropertyHandle ph = th.getPropertyHandle(TableHandle.FILTER_PROP);  
  296.   
  297.             ph.addItem(fc);  
  298.         } catch (Exception e) {  
  299.             e.printStackTrace();  
  300.         }  
  301.     }  
  302.   
  303.     void addHyperlink(LabelHandle lh) {  
  304.         try {  
  305.             Action ac = structFactory.createAction();  
  306.   
  307.             ActionHandle actionHandle = lh.setAction(ac);  
  308.             // actionHandle.setURI("'http://www.google.com'");  
  309.             actionHandle  
  310.                     .setLinkType(DesignChoiceConstants.ACTION_LINK_TYPE_DRILL_THROUGH);  
  311.             actionHandle.setReportName("d:\\TopNPercent.rptdesign");  
  312.             actionHandle.setTargetFileType("report-design");  
  313.             actionHandle.setTargetWindow("_blank");  
  314.             actionHandle.getMember("paramBindings");  
  315.             ParamBinding pb = structFactory.createParamBinding();  
  316.             pb.setParamName("order");  
  317.             pb.setExpression("row[\"ORDERNUMBER\"]");  
  318.             actionHandle.addParamBinding(pb);  
  319.   
  320.         } catch (Exception e) {  
  321.             e.printStackTrace();  
  322.         }  
  323.     }  
  324.   
  325.     void addToc(DataItemHandle dh) {  
  326.         try {  
  327.             TOC myToc = structFactory.createTOC("row[\"CustomerName\"]");  
  328.   
  329.             dh.addTOC(myToc);  
  330.         } catch (Exception e) {  
  331.             e.printStackTrace();  
  332.         }  
  333.     }  
  334.   
  335.     void addImage() {  
  336.         try {  
  337.             EmbeddedImage image = structFactory.createEmbeddedImage();  
  338.             image.setType(DesignChoiceConstants.IMAGE_TYPE_IMAGE_JPEG);  
  339.             image.setData(load("logo3.jpg"));  
  340.             image.setName("mylogo");  
  341.   
  342.             designHandle.addImage(image);  
  343.         } catch (Exception e) {  
  344.             e.printStackTrace();  
  345.         }  
  346.     }  
  347.   
  348.     public byte[] load(String fileName) throws IOException {  
  349.         InputStream is = null;  
  350.   
  351.         is = new BufferedInputStream(this.getClass().getResourceAsStream(  
  352.                 fileName));  
  353.         byte data[] = null;  
  354.         if (is != null) {  
  355.             try {  
  356.                 data = new byte[is.available()];  
  357.                 is.read(data);  
  358.             } catch (IOException e1) {  
  359.                 throw e1;  
  360.             }  
  361.         }  
  362.         return data;  
  363.     }  
  364.   
  365.     void addScript(ReportDesignHandle rh) {  
  366.         try {  
  367.             IncludeScript is = structFactory.createIncludeScript();  
  368.             is.setFileName("test.js");  
  369.             // PropertyHandle ph =  
  370.             // rh.getPropertyHandle(ReportDesign.INCLUDE_SCRIPTS_PROP);  
  371.             // ph.addItem(is);  
  372.   
  373.         } catch (Exception e) {  
  374.             e.printStackTrace();  
  375.         }  
  376.     }  
  377.   
  378.     void buildReport() throws IOException, SemanticException {  
  379.   
  380.         DesignConfig config = new DesignConfig();  
  381.         config.setBIRTHome("E:\\birt汉化包\\birt-runtime-3_7_2\\ReportEngine");  
  382.         IDesignEngine engine = null;  
  383.         try {  
  384.   
  385.             Platform.startup(config);  
  386.             IDesignEngineFactory factory = (IDesignEngineFactory) Platform  
  387.                     .createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);  
  388.             engine = factory.createDesignEngine(config);  
  389.   
  390.         } catch (Exception ex) {  
  391.             ex.printStackTrace();  
  392.         }  
  393.   
  394.         SessionHandle session = engine.newSessionHandle(ULocale.ENGLISH);  
  395.   
  396.         ReportDesignHandle design = null;  
  397.   
  398.         try {  
  399.             // open a design or a template  
  400.             designHandle = session.createDesign();  
  401.             addScript(designHandle);  
  402.             designFactory = designHandle.getElementFactory();  
  403.             buildDataSource();  
  404.             buildDataSet();  
  405.             buildJointDataSet();  
  406.   
  407.             TableHandle table = designFactory.newTableItem("table"3);  
  408.             table.setWidth("100%");  
  409.             table.setDataSet(designHandle.findDataSet("ds"));  
  410.   
  411.   
  412.             RowOperationParameters ro = new RowOperationParameters(2, -10);  
  413.             table.insertRow(ro);  
  414.   
  415.             PropertyHandle computedSet = table.getColumnBindings();  
  416.             ComputedColumn cs1, cs2, cs3, cs4, cs5;  
  417.   
  418.             cs1 = StructureFactory.createComputedColumn();  
  419.             cs1.setName("CustomerName");  
  420.             cs1.setExpression("dataSetRow[\"CUSTOMERNAME\"]");  
  421.             computedSet.addItem(cs1);  
  422.             cs2 = StructureFactory.createComputedColumn();  
  423.             cs2.setName("CustomerCity");  
  424.             cs2.setExpression("dataSetRow[\"CITY\"]");  
  425.             // cs2.setDataType(dataType)  
  426.             computedSet.addItem(cs2);  
  427.             cs3 = StructureFactory.createComputedColumn();  
  428.             cs3.setName("CustomerCountry");  
  429.             cs3.setExpression("dataSetRow[\"COUNTRY\"]");  
  430.             computedSet.addItem(cs3);  
  431.             cs4 = StructureFactory.createComputedColumn();  
  432.             cs4.setName("CustomerCreditLimit");  
  433.             cs4.setExpression("dataSetRow[\"CREDITLIMIT\"]");  
  434.             computedSet.addItem(cs4);  
  435.   
  436.             cs5 = StructureFactory.createComputedColumn();  
  437.             cs5.setName("CustomerCreditLimitSum");  
  438.             cs5.setExpression("dataSetRow[\"CREDITLIMIT\"]");  
  439.             cs5.setAggregateFunction("sum");  
  440.             computedSet.addItem(cs5);  
  441.   
  442.             // table header  
  443.             RowHandle tableheader = (RowHandle) table.getHeader().get(0);  
  444.   
  445.             ColumnHandle ch = (ColumnHandle) table.getColumns().get(0);  
  446.             ch.setProperty("width""50%");  
  447.   
  448.             ColumnHandle ch2 = (ColumnHandle) table.getColumns().get(1);  
  449.             ch2.setSuppressDuplicates(true);  
  450.   
  451.             LabelHandle label1 = designFactory.newLabel("Label1");  
  452.             label1.setOnRender("var x = 3;");  
  453.             addBottomBorder(label1);  
  454.             label1.setText("Customer");  
  455.             CellHandle cell = (CellHandle) tableheader.getCells().get(0);  
  456.   
  457.             cell.getContent().add(label1);  
  458.             LabelHandle label2 = designFactory.newLabel("Label2");  
  459.             label2.setText("City");  
  460.             cell = (CellHandle) tableheader.getCells().get(1);  
  461.             cell.getContent().add(label2);  
  462.             LabelHandle label3 = designFactory.newLabel("Label3");  
  463.             label3.setText("Credit Limit");  
  464.             cell = (CellHandle) tableheader.getCells().get(2);  
  465.   
  466.             cell.getContent().add(label3);  
  467.   
  468.             // table detail (second Detail Row)  
  469.             RowHandle tabledetail = (RowHandle) table.getDetail().get(1);  
  470.   
  471.             cell = (CellHandle) tabledetail.getCells().get(0);  
  472.             DataItemHandle data = designFactory.newDataItem("data1");  
  473.             data.setResultSetColumn("CustomerName");  
  474.   
  475.             addToc(data);  
  476.   
  477.             cell.getContent().add(data);  
  478.             cell = (CellHandle) tabledetail.getCells().get(1);  
  479.             data = designFactory.newDataItem("data2");  
  480.             data.setResultSetColumn("CustomerCity");  
  481.             cell.getContent().add(data);  
  482.             cell = (CellHandle) tabledetail.getCells().get(2);  
  483.             data = designFactory.newDataItem("data3");  
  484.             TextItemHandle tih = designFactory.newTextItem("mytextitem");  
  485.             // tih.setContentType(contentType);  
  486.             // tih.setContent(value);  
  487.             data.setResultSetColumn("CustomerCreditLimit");  
  488.             cell.getContent().add(data);  
  489.   
  490.             FormatValue fv = structFactory.newFormatValue();  
  491.             fv.setPattern("#,##0.00{RoundingMode=HALF_UP}");  
  492.             fv.setCategory("custom");  
  493.             data.setProperty("numberFormat", fv);  
  494.   
  495.             addHyperlink(label1);  
  496.             addMapRule(table);  
  497.             addHighLightRule(tabledetail);  
  498.             addSortKey(table);  
  499.             modSortKey(table);  
  500.             addFilterCondition(table);  
  501.             // addImage();  
  502.   
  503.             RowHandle tablefooter = (RowHandle) table.getFooter().get(0);  
  504.             cell = (CellHandle) tablefooter.getCells().get(0);  
  505.   
  506.             ImageHandle image1 = designFactory.newImage("mylogo");  
  507.             image1.setImageName("mylogo");  
  508.             // image1.sets  
  509.             // addVisRule( image1 );  
  510.             // cell.getContent( ).add( image1 );  
  511.   
  512.             cell = (CellHandle) tablefooter.getCells().get(2);  
  513.             data = designFactory.newDataItem("datasum");  
  514.             data.setResultSetColumn("CustomerCreditLimitSum");  
  515.   
  516.             cell.getContent().add(data);  
  517.   
  518.             ScalarParameterHandle sph = designFactory.newScalarParameter("srt");  
  519.             sph.setIsRequired(false);  
  520.             // sph.setAllowNull(true);  
  521.             // sph.setAllowBlank(true);  
  522.             sph.setValueType(DesignChoiceConstants.PARAM_VALUE_TYPE_STATIC);  
  523.             sph.setDataType(DesignChoiceConstants.PARAM_TYPE_STRING);  
  524.             designHandle.getParameters().add(sph);  
  525.   
  526.             // delete the row added earlier:  
  527.             table.getDetail().get(0).drop();  
  528.             designHandle.getBody().add(table);  
  529.             // designHandle.findElement("mytable");  
  530.   
  531.             // Save the design and close it.  
  532.   
  533.             designHandle.saveAs("d:\\structfactorytest.rptdesign");  
  534.             designHandle.close();  
  535.             Platform.shutdown();  
  536.             System.out.println("Finished");  
  537.         } catch (Exception e) {  
  538.             e.printStackTrace();  
  539.         }  
  540.   
  541.     }  
  542. }  

生成的structfactorytest.rptdesign预览如下:

第十三章 BIRT报表引擎API及报表API (续2)-利用BIRT设计引擎API生成报表_第4张图片

输入参数srt为a之后的预览如下(故意显示了目录,srt等于a意味着要根据customer逆序排序):

第十三章 BIRT报表引擎API及报表API (续2)-利用BIRT设计引擎API生成报表_第5张图片

当然我们还能设计交叉报表和分组报表,下面就是一个设计交叉报表的案例:

[java]  view plain copy
  1. package birtbird;  
  2.   
  3.   
  4. import java.io.IOException;  
  5.   
  6. import org.eclipse.birt.core.framework.Platform;  
  7. import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants;  
  8. import org.eclipse.birt.report.item.crosstab.core.de.CrosstabCellHandle;  
  9. import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle;  
  10. import org.eclipse.birt.report.item.crosstab.core.de.DimensionViewHandle;  
  11. import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle;  
  12. import org.eclipse.birt.report.item.crosstab.core.de.MeasureViewHandle;  
  13. import org.eclipse.birt.report.item.crosstab.core.util.CrosstabExtendedItemFactory;  
  14. import org.eclipse.birt.report.model.api.ComputedColumnHandle;  
  15. import org.eclipse.birt.report.model.api.DataItemHandle;  
  16. import org.eclipse.birt.report.model.api.DataSetHandle;  
  17. import org.eclipse.birt.report.model.api.DesignConfig;  
  18. import org.eclipse.birt.report.model.api.DesignElementHandle;  
  19. import org.eclipse.birt.report.model.api.ElementFactory;  
  20. import org.eclipse.birt.report.model.api.ExtendedItemHandle;  
  21. import org.eclipse.birt.report.model.api.IDesignEngine;  
  22. import org.eclipse.birt.report.model.api.IDesignEngineFactory;  
  23. import org.eclipse.birt.report.model.api.LabelHandle;  
  24. import org.eclipse.birt.report.model.api.OdaDataSetHandle;  
  25. import org.eclipse.birt.report.model.api.OdaDataSourceHandle;  
  26. import org.eclipse.birt.report.model.api.ReportDesignHandle;  
  27. import org.eclipse.birt.report.model.api.ReportItemHandle;  
  28. import org.eclipse.birt.report.model.api.SessionHandle;  
  29. import org.eclipse.birt.report.model.api.StructureFactory;  
  30. import org.eclipse.birt.report.model.api.activity.SemanticException;  
  31. import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;  
  32. import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;  
  33. import org.eclipse.birt.report.model.api.extension.IReportItem;  
  34. import org.eclipse.birt.report.model.api.olap.MeasureGroupHandle;  
  35. import org.eclipse.birt.report.model.api.olap.MeasureHandle;  
  36. import org.eclipse.birt.report.model.api.olap.TabularCubeHandle;  
  37. import org.eclipse.birt.report.model.api.olap.TabularDimensionHandle;  
  38. import org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle;  
  39. import org.eclipse.birt.report.model.api.olap.TabularLevelHandle;  
  40. import org.eclipse.birt.report.model.elements.interfaces.ICubeModel;  
  41.   
  42. import com.ibm.icu.util.ULocale;  
  43.   
  44. public class CreateDataCube  
  45. {  
  46.     ReportDesignHandle designHandle = null;  
  47.     ElementFactory designFactory = null;  
  48.     StructureFactory structFactory = null;    
  49.   
  50.     public static void main( String[] args )  
  51.     {  
  52.         try  
  53.         {  
  54.             CreateDataCube de = new CreateDataCube();         
  55.             de.buildReport();  
  56.         }  
  57.         catch ( IOException e )  
  58.         {     
  59.             e.printStackTrace();  
  60.         }  
  61.         catch ( SemanticException e )  
  62.         {  
  63.             e.printStackTrace();  
  64.         }  
  65.     }  
  66.   
  67.     void buildDataSource( ) throws SemanticException  
  68.     {  
  69.         OdaDataSourceHandle dsHandle = designFactory.newOdaDataSource(  
  70.                 "Data Source""org.eclipse.birt.report.data.oda.jdbc" );  
  71.         dsHandle.setProperty( "odaDriverClass",  
  72.         "org.eclipse.birt.report.data.oda.sampledb.Driver" );  
  73.         dsHandle.setProperty( "odaURL""jdbc:classicmodels:sampledb" );  
  74.         dsHandle.setProperty( "odaUser""ClassicModels" );  
  75.         dsHandle.setProperty( "odaPassword""" );  
  76.         designHandle.getDataSources( ).add( dsHandle );  
  77.     }  
  78.   
  79.     void buildDataSet( ) throws SemanticException  
  80.     {  
  81.         OdaDataSetHandle dsHandle = designFactory.newOdaDataSet( "ds",  
  82.         "org.eclipse.birt.report.data.oda.jdbc.JdbcSelectDataSet" );  
  83.         dsHandle.setDataSource( "Data Source" );  
  84.         String qry = "Select * from customers";  
  85.         dsHandle.setQueryText( qry );  
  86.         designHandle.getDataSets( ).add( dsHandle );  
  87.     }  
  88.     void buidCube() throws SemanticException  
  89.     {  
  90.         TabularCubeHandle cubeHandle = designHandle.getElementFactory( )  
  91.         .newTabularCube( "MyCube" );  
  92.         cubeHandle.setDataSet((DataSetHandle)designHandle.getDataSets().get(0));  
  93.         designHandle.getCubes( ).add( cubeHandle );  
  94.   
  95.         // measure group  
  96.         MeasureGroupHandle measureGroupHandle = designHandle  
  97.         .getElementFactory( ).newTabularMeasureGroup(  
  98.         "testMeasureGroup" );  
  99.         cubeHandle.setProperty( ICubeModel.MEASURE_GROUPS_PROP,  
  100.                 measureGroupHandle );  
  101.   
  102.         measureGroupHandle.add( MeasureGroupHandle.MEASURES_PROP, designFactory.newTabularMeasure( null ) );  
  103.         MeasureHandle measure = (MeasureHandle) measureGroupHandle.getContent(MeasureGroupHandle.MEASURES_PROP, 0 );  
  104.         measure.setName( "CREDITLIMIT" );  
  105.         measure.setMeasureExpression( "dataSetRow['CREDITLIMIT']" );  
  106.         measure.setFunction( DesignChoiceConstants.MEASURE_FUNCTION_SUM );  
  107.         measure.setCalculated( false );  
  108.         measure.setDataType( DesignChoiceConstants.COLUMN_DATA_TYPE_FLOAT );  
  109.   
  110.         TabularDimensionHandle dimension =  designFactory.newTabularDimension( null );  
  111.         cubeHandle.add(TabularCubeHandle.DIMENSIONS_PROP, dimension  );  
  112.         dimension.setTimeType( false );  
  113.   
  114.         dimension.add( TabularDimensionHandle.HIERARCHIES_PROP, designFactory.newTabularHierarchy( null ) );      
  115.         TabularHierarchyHandle hierarchy = (TabularHierarchyHandle) dimension.getContent( TabularDimensionHandle.HIERARCHIES_PROP, 0 );  
  116.   
  117.         hierarchy.setDataSet( (DataSetHandle)designHandle.getDataSets().get(0) );   
  118.   
  119.         hierarchy.add( TabularHierarchyHandle.LEVELS_PROP, designFactory.newTabularLevel( dimension, null ) );  
  120.         TabularLevelHandle level = (TabularLevelHandle) hierarchy.getContent(TabularHierarchyHandle.LEVELS_PROP, 0 );  
  121.         level.setName( "testlevel" );  
  122.         level.setColumnName( "CUSTOMERNAME" );  
  123.         level.setDataType( DesignChoiceConstants.COLUMN_DATA_TYPE_STRING );  
  124.   
  125.         ExtendedItemHandle xtab = CrosstabExtendedItemFactory.createCrosstabReportItem(designHandle, cubeHandle, "MyCrosstab" );  
  126.         designHandle.getBody().add(xtab);  
  127.   
  128.   
  129.         IReportItem reportItem = xtab.getReportItem( );  
  130.         CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) reportItem;  
  131.         DimensionViewHandle dvh = xtabHandle.insertDimension(dimension, ICrosstabConstants.ROW_AXIS_TYPE, 0);  
  132.         LevelViewHandle levelViewHandle =dvh.insertLevel(level, 0);  
  133.         CrosstabCellHandle cellHandle = levelViewHandle.getCell( );  
  134.         DesignElementHandle eii = xtabHandle.getModelHandle( );  
  135.   
  136.         ComputedColumn bindingColumn = StructureFactory.newComputedColumn( eii, level.getName( ) );  
  137.         ComputedColumnHandle bindingHandle = ((ReportItemHandle) eii).addColumnBinding( bindingColumn,false );  
  138.         bindingColumn.setDataType( level.getDataType( ) );  
  139.         String exp = "dimension['" + dimension.getName()+"']['"+level.getName()+"']";  
  140.         bindingColumn.setExpression( exp);  
  141.   
  142.         DataItemHandle dataHandle = designFactory.newDataItem( level.getName( ) );  
  143.         dataHandle.setResultSetColumn( bindingHandle.getName( ) );  
  144.         cellHandle.addContent( dataHandle );  
  145.   
  146.         MeasureViewHandle mvh = xtabHandle.insertMeasure(measure, 0);  
  147.         //mvh.addHeader( );  
  148.   
  149.         LabelHandle labelHandle = designFactory.newLabel( null );  
  150.         labelHandle.setText( measure.getName() );  
  151.         mvh.getHeader( ).addContent( labelHandle );  
  152.   
  153.     }  
  154.   
  155.   
  156.     void buildReport() throws IOException, SemanticException  
  157.     {  
  158.   
  159.         DesignConfig config = new DesignConfig( );  
  160.         config.setBIRTHome("E:\\birt汉化包\\birt-runtime-3_7_2\\ReportEngine");  
  161.         IDesignEngine engine = null;  
  162.         try{  
  163.             Platform.startup( config );  
  164.             IDesignEngineFactory factory = (IDesignEngineFactory) Platform  
  165.             .createFactoryObject( IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY );  
  166.             engine = factory.createDesignEngine( config );  
  167.         }catch( Exception ex){  
  168.             ex.printStackTrace();  
  169.         }  
  170.   
  171.         SessionHandle session = engine.newSessionHandle( ULocale.ENGLISH ) ;  
  172.   
  173.         try{  
  174.             //open a design or a template  
  175.             designHandle = session.createDesign();  
  176.   
  177.             designFactory = designHandle.getElementFactory( );  
  178.   
  179.             buildDataSource();  
  180.             buildDataSet();  
  181.             buidCube();  
  182.   
  183.             // Save the design and close it.  
  184.   
  185.             designHandle.saveAs("d:\\cubetest.rptdesign" );  
  186.             designHandle.close( );  
  187.             Platform.shutdown();  
  188.             System.out.println("Finished");  
  189.         }catch (Exception e){  
  190.             e.printStackTrace();  
  191.         }         
  192.   
  193.     }  
  194. }  

生成的cubetest.rptdesign预览如下:


下面是一个设计图表的例子:

[java]  view plain copy
  1. package birtbird;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import org.eclipse.birt.chart.model.Chart;  
  6. import org.eclipse.birt.chart.model.ChartWithAxes;  
  7. import org.eclipse.birt.chart.model.attribute.AxisType;  
  8. import org.eclipse.birt.chart.model.attribute.IntersectionType;  
  9. import org.eclipse.birt.chart.model.attribute.LegendItemType;  
  10. import org.eclipse.birt.chart.model.attribute.Palette;  
  11. import org.eclipse.birt.chart.model.attribute.TickStyle;  
  12. import org.eclipse.birt.chart.model.attribute.impl.ColorDefinitionImpl;  
  13. import org.eclipse.birt.chart.model.attribute.impl.PaletteImpl;  
  14. import org.eclipse.birt.chart.model.component.Axis;  
  15. import org.eclipse.birt.chart.model.component.Series;  
  16. import org.eclipse.birt.chart.model.component.impl.SeriesImpl;  
  17. import org.eclipse.birt.chart.model.data.BaseSampleData;  
  18. import org.eclipse.birt.chart.model.data.DataFactory;  
  19. import org.eclipse.birt.chart.model.data.OrthogonalSampleData;  
  20. import org.eclipse.birt.chart.model.data.SampleData;  
  21. import org.eclipse.birt.chart.model.data.SeriesDefinition;  
  22. import org.eclipse.birt.chart.model.data.impl.QueryImpl;  
  23. import org.eclipse.birt.chart.model.data.impl.SeriesDefinitionImpl;  
  24. import org.eclipse.birt.chart.model.impl.ChartWithAxesImpl;  
  25. import org.eclipse.birt.chart.model.layout.Legend;  
  26. import org.eclipse.birt.chart.model.layout.Plot;  
  27. import org.eclipse.birt.chart.model.type.LineSeries;  
  28. import org.eclipse.birt.chart.model.type.impl.LineSeriesImpl;  
  29. import org.eclipse.birt.core.framework.Platform;  
  30. import org.eclipse.birt.report.model.api.DesignConfig;  
  31. import org.eclipse.birt.report.model.api.ElementFactory;  
  32. import org.eclipse.birt.report.model.api.ExtendedItemHandle;  
  33. import org.eclipse.birt.report.model.api.IDesignEngine;  
  34. import org.eclipse.birt.report.model.api.IDesignEngineFactory;  
  35. import org.eclipse.birt.report.model.api.OdaDataSetHandle;  
  36. import org.eclipse.birt.report.model.api.OdaDataSourceHandle;  
  37. import org.eclipse.birt.report.model.api.ReportDesignHandle;  
  38. import org.eclipse.birt.report.model.api.SessionHandle;  
  39. import org.eclipse.birt.report.model.api.SimpleMasterPageHandle;  
  40. import org.eclipse.birt.report.model.api.StructureFactory;  
  41. import org.eclipse.birt.report.model.api.activity.SemanticException;  
  42. import org.eclipse.birt.report.model.api.command.ContentException;  
  43. import org.eclipse.birt.report.model.api.command.NameException;  
  44. import org.eclipse.birt.report.model.api.elements.structures.PropertyBinding;  
  45.   
  46. import com.ibm.icu.util.ULocale;  
  47.   
  48.   
  49. public class SimpleChart  
  50.   
  51. {  
  52.   
  53.     private ReportDesignHandle reportDesignHandle = null;  
  54.   
  55.     private ElementFactory elementFactory = null;  
  56.   
  57.     private OdaDataSourceHandle odaDataSourceHandle = null;  
  58.   
  59.     private String dataSourceName = "datasource";  
  60.   
  61.     private String dataSetName = "maindataset";  
  62.     private SessionHandle sessionHandle =null;  
  63.   
  64.     org.eclipse.birt.report.model.api.elements.structures.ComputedColumn cs1, cs2 = null;  
  65.   
  66.     public static void main(String args[])  
  67.   
  68.     {  
  69.         try {  
  70.   
  71.             new SimpleChart().createReport();  
  72.   
  73.         } catch (Exception e) {  
  74.   
  75.             e.printStackTrace();  
  76.   
  77.         }  
  78.   
  79.     }  
  80.   
  81.   
  82.     public void createReport() throws SemanticException, IOException  
  83.   
  84.     {  
  85.         System.out.println("Start");  
  86.         init();  
  87.   
  88.         createMasterPages();  
  89.   
  90.         buildDataSource();  
  91.         buildDataSet();          
  92.         createBody();  
  93.           
  94.         reportDesignHandle.saveAs("d:\\simplechart.rptdesign");    
  95.         reportDesignHandle.close( );  
  96.         Platform.shutdown();  
  97.         System.out.println("Finished");          
  98.   
  99.     }  
  100.   
  101.   
  102.     private void init(){  
  103.   
  104.   
  105.         DesignConfig config = new DesignConfig( );  
  106.         config.setBIRTHome("");  
  107.         IDesignEngine engine = null;  
  108.   
  109.         try {  
  110.   
  111.             Platform.startup(config);  
  112.   
  113.             IDesignEngineFactory factory = (IDesignEngineFactory) Platform  
  114.   
  115.             .createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);  
  116.   
  117.             engine = factory.createDesignEngine(config);  
  118.   
  119.         } catch (Exception ex) {  
  120.   
  121.             ex.printStackTrace();  
  122.   
  123.         }  
  124.   
  125.         sessionHandle = engine.newSessionHandle(ULocale.ENGLISH);  
  126.         reportDesignHandle = sessionHandle.createDesign();  
  127.         elementFactory = reportDesignHandle.getElementFactory();  
  128.   
  129.     }  
  130.   
  131.   
  132.     private void createMasterPages() throws ContentException, NameException  
  133.     {  
  134.         SimpleMasterPageHandle simpleMasterPage =  
  135.             elementFactory.newSimpleMasterPage("Master Page");  
  136.         reportDesignHandle.getMasterPages().add(simpleMasterPage);  
  137.   
  138.     }  
  139.   
  140.     void buildDataSource( ) throws SemanticException  
  141.     {  
  142.         OdaDataSourceHandle dsHandle = elementFactory.newOdaDataSource(  
  143.                 "Data Source""org.eclipse.birt.report.data.oda.jdbc" );  
  144.         dsHandle.setProperty( "odaDriverClass",  
  145.         "org.eclipse.birt.report.data.oda.sampledb.Driver" );  
  146.         dsHandle.setProperty( "odaURL""jdbc:classicmodels:sampledb" );  
  147.         dsHandle.setProperty( "odaUser""ClassicModels" );  
  148.         dsHandle.setProperty( "odaPassword""" );        
  149.         PropertyBinding pb = new PropertyBinding();  
  150.         reportDesignHandle.getDataSources( ).add( dsHandle );  
  151.   

你可能感兴趣的:(第十三章 BIRT报表引擎API及报表API (续2)-利用BIRT设计引擎API生成报表)