首页 > 其他分享 >利用BIRT API生成报表例子2

利用BIRT API生成报表例子2

时间:2023-05-24 13:00:57浏览次数:35  
标签:报表 get api factory birt BIRT API org import


package com.demo;

public class Bean
{
	private String name;
	private int age;
	private String city;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}

}




package com.demo;


import java.util.ArrayList;
import java.util.List;

public class Factory
{
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List getData()
	{
		Bean b1=new Bean();
		b1.setName("张三");
		b1.setAge(18);
		b1.setCity("西安");

		Bean b2=new Bean();
		b2.setName("李四");
		b2.setAge(25);
		b2.setCity("北京");

		Bean b3=new Bean();
		b3.setName("王五");
		b3.setAge(40);
		b3.setCity("深圳");

		Bean b4=new Bean();
		b4.setName("陈六");
		b4.setAge(30);
		b4.setCity("香港");

		Bean b5=new Bean();
		b5.setName("Jack");
		b5.setAge(30);
		b5.setCity("New York");

		Bean b6=new Bean();
		b6.setName("Tom");
		b6.setAge(30);
		b6.setCity("London");

		Bean b7=new Bean();
		b7.setName("Jim");
		b7.setAge(30);
		b7.setCity("LA");

		List list=new ArrayList();
		list.add(b1);
		list.add(b2);
		list.add(b3);
		list.add(b4);
		list.add(b5);
		list.add(b6);
		list.add(b7);
		return list;
	}

}




package com.demo;

import java.util.ArrayList;
import java.util.List;

public class TestData
{
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List getColumn()
	{
		List list=new ArrayList();

		String[] strArray=new String [3];
		strArray[0]="CPU,显示器";
		strArray[1]="利用率1,利用率2,磁盘";
		strArray[2]="空闲率";

		String[] strArray2=new String [2];
		strArray2[0]="磁盘";
		strArray2[1]="吞吐量";

		String[] strArray3=new String [4];
		strArray3[0]="内存";
		strArray3[1]="内存量,二级缓存";
		strArray3[2]="最大利用率";
		strArray3[3]="测试1,测试2,测试3";

		list.add(strArray);
		list.add(strArray2);
		list.add(strArray3);
		return list;
	}

}



[b][color=red]主要程序代码[/color][/b]


package com.demo;

import java.io.IOException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.model.api.CellHandle;
import org.eclipse.birt.report.model.api.DataItemHandle;
import org.eclipse.birt.report.model.api.DesignConfig;
import org.eclipse.birt.report.model.api.DesignElementHandle;
import org.eclipse.birt.report.model.api.ElementFactory;
import org.eclipse.birt.report.model.api.GridHandle;
import org.eclipse.birt.report.model.api.IDesignEngine;
import org.eclipse.birt.report.model.api.IDesignEngineFactory;
import org.eclipse.birt.report.model.api.ImageHandle;
import org.eclipse.birt.report.model.api.LabelHandle;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.birt.report.model.api.ReportDesignHandle;
import org.eclipse.birt.report.model.api.RowHandle;
import org.eclipse.birt.report.model.api.ScriptDataSetHandle;
import org.eclipse.birt.report.model.api.ScriptDataSourceHandle;
import org.eclipse.birt.report.model.api.SessionHandle;
import org.eclipse.birt.report.model.api.SlotHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.StyleHandle;
import org.eclipse.birt.report.model.api.TableHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.structures.CachedMetaData;
import org.eclipse.birt.report.model.api.elements.structures.ColumnHint;
import org.eclipse.birt.report.model.api.elements.structures.ComputedColumn;
import org.eclipse.birt.report.model.api.elements.structures.ResultSetColumn;

import com.ibm.icu.util.ULocale;

/**
 * 
 * @author ZYJ
 * 
 */
public class Demo4 {
	public static void main(String[] args) {
		try {

			buildReport();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SemanticException e) {
			e.printStackTrace();
		}
	}

	static void buildReport() throws IOException, SemanticException {
		DesignConfig config = new DesignConfig();
		config.setProperty("BIRT_HOME", "F:/movie/birt-runtime-2_5_1/birt-runtime-2_5_1/ReportEngine");
		IDesignEngine engine = null;
		try {
			Platform.startup(config);
			IDesignEngineFactory factory = (IDesignEngineFactory) Platform
					.createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY);
			engine = factory.createDesignEngine(config);
		} catch (Exception e) {
			e.printStackTrace();
		}
		SessionHandle session = engine.newSessionHandle(ULocale.CHINESE);
		ReportDesignHandle design = session.createDesign();
		ElementFactory factory = design.getElementFactory();
		DesignElementHandle element = factory.newSimpleMasterPage("Demo3");
		design.getMasterPages().add(element);

		// ///
		ScriptDataSourceHandle datasource = buidDataSource(factory);
		ScriptDataSetHandle dataset = createScript(datasource, factory);
		design.getDataSources().add(datasource);
		design.getDataSets().add(dataset);
		SetStyle(design, factory);
		// /
		createTitle("磁盘IO吞吐量报表", "admin", "2009-10-01 00:00:00", "2009-11-15 00:00:00", design, factory);
		TableHandle table = factory.newTableItem(null, 3);
		table.setWidth("100%");
		table.setDataSet(dataset);
		design.getBody().add(table);
		RowHandle tableheader = (RowHandle) table.getHeader().get(0);
		createColumn(TestData.getColumn(), tableheader, factory);
		RowHandle tablebody = (RowHandle) table.getDetail().get(0);
		initBody(TestData.getColumn(), tablebody, factory);

		// //
		// /将数据集绑定要表格中

		PropertyHandle computedSet = table.getColumnBindings();
		ComputedColumn computedColum = null;
		computedColum = StructureFactory.createComputedColumn();
		computedColum.setName("name");
		computedColum.setExpression("dataSetRow['name']");
		computedSet.addItem(computedColum);
		ComputedColumn computedColum2 = null;
		computedColum2 = StructureFactory.createComputedColumn();
		computedColum2.setName("age");
		computedColum2.setExpression("dataSetRow['age']");
		computedSet.addItem(computedColum2);
		ComputedColumn computedColum3 = null;
		computedColum3 = StructureFactory.createComputedColumn();
		computedColum3.setName("city");
		computedColum3.setExpression("dataSetRow['city']");
		computedSet.addItem(computedColum3);

		CellHandle celltotal = (CellHandle) tablebody.getCells().get(0);
		SlotHandle grid = celltotal.getContent();
		GridHandle grid2 = (GridHandle) grid.get(0);
		RowHandle row = (RowHandle) grid2.getRows().get(0);
		CellHandle cell = (CellHandle) row.getCells().get(0);
		DataItemHandle data = factory.newDataItem("data_name");
		data.setResultSetColumn("name");
		cell.getContent().add(data);

		CellHandle cella = (CellHandle) tablebody.getCells().get(1);
		SlotHandle grida = cella.getContent();
		GridHandle grida2 = (GridHandle) grida.get(1);
		RowHandle rowa = (RowHandle) grida2.getRows().get(0);
		CellHandle cellaa = (CellHandle) rowa.getCells().get(0);
		DataItemHandle dataa = factory.newDataItem("data_age");
		dataa.setResultSetColumn("age");
		cellaa.getContent().add(dataa);

		ImageHandle image = factory.newImage(null);
		CellHandle celltotalimg = (CellHandle) tablebody.getCells().get(2);
		GridHandle gridimg = (GridHandle) celltotalimg.getContent().get(0);
		RowHandle rowimg = (RowHandle) gridimg.getRows().get(0);
		CellHandle cellimg = (CellHandle) rowimg.getCells().get(0);

		image.setFile("\"D:/lineXY.png\"");
		image.setProperty("height", "200px");
		image.setProperty("width", "300px");
		cellimg.getContent().add(image);

		CellHandle cellb = (CellHandle) tablebody.getCells().get(0);
		SlotHandle gridb = cellb.getContent();
		GridHandle gridb2 = (GridHandle) gridb.get(2);
		RowHandle rowb = (RowHandle) gridb2.getRows().get(0);
		CellHandle cellbb = (CellHandle) rowb.getCells().get(0);
		DataItemHandle datab = factory.newDataItem("data_city");
		datab.setResultSetColumn("city");
		cellbb.getContent().add(datab);
		// /

		// /
		design.saveAs("d:/demo.rptdesign");
		design.close();
		System.out.println("Finished");
	}

	/**
	 * 
	 * @param text
	 *            报表模板标题
	 * @param userId
	 *            产生用户
	 * @param start
	 *            开始时间
	 * @param end
	 *            结束时间
	 * @param design
	 *            报表实例
	 * @param factory
	 *            birt报表元素工厂
	 * @throws SemanticException
	 */
	public static void createTitle(String text, String userId, String start, String end, ReportDesignHandle design,
			ElementFactory factory) throws SemanticException {
		LabelHandle title = factory.newLabel(null);
		title.setText(text);
		design.getBody().add(title);
		title.setProperty(StyleHandle.FONT_SIZE_PROP, "20");
		title.setProperty(StyleHandle.TEXT_ALIGN_PROP, "center");
		title.setProperty(StyleHandle.FONT_WEIGHT_PROP, "Bold");
		LabelHandle subhead = factory.newLabel(null);
		subhead.setText("报表用户:" + userId + "  时间范围:" + start + "至" + end);
		design.getBody().add(subhead);
		subhead.setProperty(StyleHandle.FONT_SIZE_PROP, "12");
		subhead.setProperty(StyleHandle.TEXT_ALIGN_PROP, "center");
		subhead.setProperty(StyleHandle.FONT_WEIGHT_PROP, "Bold");
	}

	// 初始化表头
	@SuppressWarnings("rawtypes")
	public static void createColumn(List columnlist, RowHandle row, ElementFactory factory) throws SemanticException {
		logger.info("rpt info:zyj 开始初始化表头结构");
		for (int i = 0; i < columnlist.size(); i++) {
			String[] columnarry = (String[]) columnlist.get(i);
			CellHandle cell = (CellHandle) row.getCells().get(i);
			GridHandle gridcell = factory.newGridItem(null, 1, 1);
			cell.getContent().add(gridcell);
			cell.setStyleName("BorderStyle");
			for (int j = 0; j < columnarry.length; j++) {
				String[] columnrow = columnarry[j].split(",");
				GridHandle grid = factory.newGridItem(null, columnrow.length, 1); // 插入一个grid
				// cell.getContent().add(grid);
				RowHandle row2 = (RowHandle) gridcell.getRows().get(0);
				((CellHandle) row2.getCells().get(0)).getContent().add(grid);
				RowHandle temprow = (RowHandle) grid.getRows().get(0);
				for (int k = 0; k < columnrow.length; k++) {
					LabelHandle label = factory.newLabel(null);
					CellHandle tempcell = (CellHandle) temprow.getCells().get(k);
					tempcell.setStyleName("BorderStyle");
					tempcell.getContent().add(label);
					label.setText(columnrow[k]);
				}
			}
		}
		logger.info("rpt info:zyj 表头结构初始化完成");
	}

	// //初始化表体
	@SuppressWarnings({ "rawtypes", "unused" })
	public static void initBody(List columnlist, RowHandle row, ElementFactory factory) throws SemanticException {
		logger.info("rpt info:zyj 开始初始化表体结构结构");
		for (int i = 0; i < columnlist.size(); i++) {
			String[] columnarry = (String[]) columnlist.get(i);
			CellHandle cell = (CellHandle) row.getCells().get(i);
			cell.setStyleName("BorderStyle");
			for (int j = 0; j < columnarry.length; j++) {
				String[] columnrow = columnarry[j].split(",");
				GridHandle grid = factory.newGridItem(null, columnrow.length, 1); // 插入一个grid
				cell.getContent().add(grid);
				RowHandle temprow = (RowHandle) grid.getRows().get(0);

				for (int k = 0; k < columnrow.length; k++) {
					LabelHandle label = factory.newLabel(null);
					CellHandle tempcell = (CellHandle) temprow.getCells().get(k);
					tempcell.setStyleName("BorderStyle");
				}

			}
		}
		logger.info("rpt info:zyj 表体结构初始化完成");
	}

	// /创建数据源
	public static ScriptDataSourceHandle buidDataSource(ElementFactory factory) throws SemanticException {
		ScriptDataSourceHandle datasource = factory.newScriptDataSource("Datasource");
		return datasource;

	}

	// //创建数据集
	public static ScriptDataSetHandle createScript(ScriptDataSourceHandle datasource, ElementFactory factory)
			throws SemanticException {
		ScriptDataSetHandle dataset = factory.newScriptDataSet("Dataset");
		dataset.setDataSource("Datasource");
		addFlowResult(dataset);
		dataset.setOpen("importPackage(Packages.birt); emps = Factory.getData(); iterator = emps.iterator();");
		dataset.setFetch("if(iterator.hasNext()==false)   {return false;}  var emp=iterator.next(); row[1]=emp.getName() ;row[2]=emp.getAge(); row[3]=emp.getCity(); return true;");
		dataset.setClose("emps=null;iterator = null;emp = null;");
		return dataset;
	}

	// ///设定数据集输出列
	public static ScriptDataSetHandle addFlowResult(ScriptDataSetHandle dataset) throws SemanticException {
		PropertyHandle resultSet = dataset.getPropertyHandle(ScriptDataSetHandle.RESULT_SET_HINTS_PROP);

		ResultSetColumn rs1 = StructureFactory.createResultSetColumn();
		rs1.setPosition(1);
		rs1.setColumnName("name");
		rs1.setDataType("String");
		resultSet.addItem(rs1);
		ResultSetColumn rs2 = StructureFactory.createResultSetColumn();
		rs2.setPosition(2);
		rs2.setColumnName("age");
		rs2.setDataType("Integer");
		resultSet.addItem(rs2);
		ResultSetColumn rs3 = StructureFactory.createResultSetColumn();
		rs3.setPosition(3);
		rs3.setColumnName("city");
		rs3.setDataType("String");
		resultSet.addItem(rs3);
		resultSet = dataset.getPropertyHandle(ScriptDataSetHandle.COLUMN_HINTS_PROP);
		ColumnHint columnHint1 = StructureFactory.createColumnHint();
		columnHint1.setProperty("columnName", "name");
		resultSet.addItem(columnHint1);
		ColumnHint columnHint2 = StructureFactory.createColumnHint();
		columnHint2.setProperty("columnName", "age");
		resultSet.addItem(columnHint2);
		ColumnHint columnHint3 = StructureFactory.createColumnHint();
		columnHint3.setProperty("columnName", "city");
		resultSet.addItem(columnHint3);
		CachedMetaData cache = StructureFactory.createCachedMetaData();
		dataset.setCachedMetaData(cache);
		return dataset;
	}

	// //设定style
	public static void SetStyle(ReportDesignHandle design, ElementFactory factory) throws SemanticException {
		StyleHandle BorderStyle = factory.newStyle("BorderStyle");
		BorderStyle.setProperty(StyleHandle.BORDER_TOP_STYLE_PROP, "Groove");
		BorderStyle.setProperty(StyleHandle.BORDER_BOTTOM_STYLE_PROP, "Groove");
		BorderStyle.setProperty(StyleHandle.BORDER_LEFT_STYLE_PROP, "Groove");
		BorderStyle.setProperty(StyleHandle.BORDER_RIGHT_STYLE_PROP, "Groove");
		BorderStyle.setProperty(StyleHandle.BORDER_BOTTOM_WIDTH_PROP, "1px");
		BorderStyle.setProperty(StyleHandle.BORDER_LEFT_WIDTH_PROP, "1px");
		BorderStyle.setProperty(StyleHandle.BORDER_RIGHT_WIDTH_PROP, "1px");
		BorderStyle.setProperty(StyleHandle.BORDER_TOP_WIDTH_PROP, "1px");
		design.getStyles().add(BorderStyle);
	}

	private static final Log logger = LogFactory.getLog(Demo4.class);

}
// 最近这几天一直在研究birt报表,这个是这几天研究的结果,发上来大家一起分享下,如何使用birt的api完整的创建一个报表,由于我这个只是个例子,很多东西都是写死的,
// //不过还是希望能对正在学习birt api使用的各位朋友有所帮助,最近又在研究birt api的参数传递,话说这资料更少了,头痛

标签:报表,get,api,factory,birt,BIRT,API,org,import
From: https://blog.51cto.com/u_3871599/6338695

相关文章

  • vue自动导入组件和自动导入类库 api
    vue3项目中,使用vue常用的api比如vuex的api或者ref,reactive等,以及导入多个自定义组件、UI组件库的组件,都需要反复的手动导入,注册,很是影响开发体验,这里推荐antfu开源的两个插件,上链接:自动导入组件https://github.com/antfu/unplugin-vue-components自动导入类库a......
  • 报表定制系统,让报表随需而动
    作为企业管理者,我们每天都需要关注各种数据和信息,以便做出正确的商业决策。然而,这些数据和信息通常分散在不同的系统、应用程序和文件中,如果要手工收集和整理,不仅费时费力,而且容易出错。因此,为了更高效地管理数据和信息,我们需要一个强大的报表定制系统。编辑搜图什么是报表定制系统......
  • 免费API查询法定节假日
    API:https://timor.tech/api/holiday/year/2023请求结果示例{"code":0,"holiday":{"01-01":{"holiday":true,"name":"元旦","wa......
  • 关于皕杰报表的序列生成函数
    在做报表的时候,经常需要生成一个序列,比如:字母序列a、b、c、d、e...皕杰报表本身提供了list函数来生成有限的枚举序列,使用如下:语法:list(valueExp1{,valueExp2{,valueExp3{,……}}})参数说明:valueExp(n)  可以是字符型数据,整型数据,浮点型数据,布尔型数据或表达式举例说明:例1:li......
  • APIO 2023 真·旅游记
    Day0不知道为什么能来线上,就当来南京旅游了。前一周被感冒折磨的要死,爸妈阳了还不能回家,状态非常非常差,上周末还去深圳打了gdcpc。很累。早上六点钟起床,赶七点半的飞机,大概十点就到了。下飞机发现APIO的老师在迎接我们,等到十一点之后就出发去了酒店。车上甚至有桌子,其他人......
  • dom、js原生常用api, 兼容ie等主流浏览器(持续更新)
    开发组件库必须知道的东西/***获取scrollTop*@param{HTMLElement|window}element-dom元素或者window对象*@returns{number}*/functiongetScrollTop(element){if(element===window){returnwindow.pageYOffset||document.documentElemen......
  • 记录--使用率比较低的10个Web API
    这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助avaScript中有些API可能使用率比较低,下面我们逐一介绍它们的用法和使用场景。至于标题,主要是想让你进来看看,兄弟们别打我!BlobAPIBlobAPI用于处理二进制数据,可以方便地将数据转换为Blob对象或从Blob对象读取数......
  • 皕杰报表设计器在macOS上启动的问题
    最近,很多皕杰报表的使用者遇到了下载MacOS版本后,报表设计器初次启动,不能正常打开的问题。这主要是由于报表设计器找不到Java导致的。可以打开BIOSStudio.app\Contents\Eclipse\下的BIOSStudio.ini,在-vmargs参数之前添加-vm参数来指定您操作系统安装的Java,即可如下所示:-startup......
  • java api调用kafka
    已经启用了zookeeper和kafka单机的ip为192.168.80.128加入maven的pom.xml代码如下 <dependency><groupId>org.apache.kafka</groupId><artifactId>kafka-clients</artifactId><version>0.8.2.1</version&g......
  • Uni-app 封装 API 请求
    一、在文件夹API下创建api.jsconstBASE_URL="";//封装请求方法constrequest=(url,method,data)=>{ wx.showLoading({ title:'加载中'//数据请求前loading }) returnnewPromise((resolve,reject)=>{ wx.request({ url:BASE_URL+url,......