如何利用C++ Builder實現(xiàn)對Excel97 的調(diào)用
2019-09-06 23:33:46
供稿:網(wǎng)友
我們在進(jìn)行數(shù)據(jù)庫軟件的開發(fā)時,一般都要進(jìn)行大量的報表設(shè)計,雖然我們可以利用crystal report 或程序自帶的報表工具進(jìn)行報表設(shè)計,但是當(dāng)涉及到要設(shè)計多重報表或交叉報表時、我們一般都會感到自己力不從心。有時雖然想利用excel作為前臺報表,但卻找不到相關(guān)接口只能作罷。其實我們只要知道excel的接口結(jié)構(gòu),就能夠方便的實現(xiàn)對excel的調(diào)用。
原理:在excel 中程序接口一般分為3層 ,分別為:exelapplication、excelbook、excelsheet 其中exelapplication代表excel程序,excelbook代表excel程序當(dāng)前的工作本,excelsheet代表excelbook當(dāng)前激活的表格,因此在啟動excel程序時要按此序分別啟動,這樣就能實現(xiàn)對excel報表的操作。
現(xiàn)舉例為例介紹如下:
一、在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);//創(chuàng)建只含有一個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)
{//添加數(shù)據(jù)//
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->filedname);//在指定的位置加入字段名//
table1->first();
j=2;
while( !table1->eof( ))
{
for( i=0;i<table1->fieldcount;i++)
worksheet->cells->set__default(j,i, table1->fields->fileds->asstring);////在指定的位置加入數(shù)據(jù)庫的內(nèi)容//
table1->next( );
j++;
}
}
六、在button3的onclikc事件中添加如下代碼:
void __fastcall tform1::button3click(tobject *sender)
{//表格設(shè)置//
range = m_worksheet->get_range("c1:f20");//設(shè)置表格操作范圍//
range->font->size=12;//設(shè)置字體大小//
range->columns->interior->colorindex = 3;//設(shè)置表格表格顏色//
range->borders->linestyle = xlcontinuous;//設(shè)置表格邊框//
firstcol = m_worksheet->columns->get__default(3 );//取得當(dāng)前表格的第三列對象//
firstcol->columnwidth = 25; // 設(shè)置對象寬度//
firstcol->font->bold = true; // 設(shè)置字體屬性為加粗//
firstcol->font->italic = true; file://設(shè)置字體的種類//
firstcol->font->color = clblue; // 設(shè)置字體的顏色//
}
以上程序在c++ builder 4.0 enterprise + pwin98中實現(xiàn)。
通過以上程序可以看出,只要我們在程序中對excel進(jìn)行巧妙的設(shè)置,就能夠設(shè)計出具有專業(yè)水平的報表。