我们在进行数据库
软件的开发时,一般都要进行大量的报表设计,虽然我们可以利用crystal report 或程序自带的报表工具进行报表设计,但是当涉及到要设计多重报表或交叉报表时、我们一般都会感到自己力不从心。有时虽然想利用excel作为前台报表,但却找不到相关接口只能作罢。其实我们只要知道excel的接口结构,就能够方便的实现对excel的调用。
原理:在excel 中程序接口一般分为3层 ,分别为:exelapplication、excelbook、excelsheet 其中exelapplication代表excel程序,excelbook代表excel程序当前的工作本,excelsheet代表excelbook当前激活的表格,因此在启动excel程序时要按此序分别启动,这样就能实现对excel报表的操作。
现举例为例介绍如下:
一、在import type library中加入 excel8.olb,在\include 子目录下生成excel_tlb.h文件.
二、在bcb4.0中form1中添加button1、button2、button3、table1,并存盘为project1。
三、在unit1.h中加入头文件 #include "..\excel_tlb.h"
在private中加入
private:
tcom_application application; file://定义excelapplication对象//
worksheetptr worksheet; // 定义excelsheet对象//
rangeptr firstcol ; file://定义列对象//
rangeptr range file://定义表格操作范围//
四、在button1的onclikc事件中添加如下代码:
void __fastcall tform1::button1click(tobject *sender)
{//启动excel//
const int xlwbatchart = -4109;
const int xlwbatworksheet = -4167;
if (! application)
application = coapplication_::create(); file://建立于excel程序的连接//
application->set_visible(0, true);//打开excel程序//
application->workbooks->add(xlwbatworksheet);//创建只含有一个excelsheet的excelbook//
worksheet = application->workbooks->get_item(1)->worksheets->get_item(1);//取得该表对象//
worksheet->name = widestring("database date");//建立该表的名称//
}
五、在button2的onclikc事件中添加如下代码:
void __fastcall tform1::button2click(tobject *sender)
{//添加数据//
int i, j;
table1->databasename="dbdemos";
table1->tablename="author.db";
table1->open( );
for( i=0;i<table1->fieldcount;i++)
worksheet->cells->set__default(1,i,table1->fileds->fileds[i]->filedname);//在指定的位置加入字段名//
table1->first();
j=2;
while( !table1->eof( ))
{
for( i=0;i<table1->fieldcount;i++)
worksheet->cells->set__default(j,i, table1->fields->fileds[i]->asstring);////在指定的位置加入数据库的内容//
table1->next( );
j++;
}
}