用VB控制EXCEL生成報表
2024-07-21 02:20:54
供稿:網友
中國最大的web開發資源網站及技術社區,
做為一種簡捷、系統的 windows應用程序開發工具,visual basic 5 具有強大的數據處理功能,提供了多種數據訪問方法,可以方便地存取microsoft sql server、oracle、xbase等多種數據庫,被廣泛應用于建立各種信息管理系統。但是,vb缺乏足夠的、符合中文習慣的數據表格輸出功能,雖然使用crystal report控件及 crystal reports程序可以輸出報表,但操作起來很麻煩,中文處理能力也不理想。excel作為micorsoft公司的表格處理軟件在表格方面有著強大的功能,我們可用vb5編寫直接控制excel操作的程序,方法是用vb的ole自動化技術獲取excel 97 的控制句柄,從而直接控制excel 97的一系列操作。
下面給出一個實例:
首先建立一個窗體(form1)在窗體中加入一個data控件和一按鈕,引用microsoft excel類型庫:從"工程"菜單中選擇"引用"欄;選擇microsoft excel 8.0 object library;選擇"確定"。
在form的load事件中加入:
data1.databasename = 數據庫名稱
data1.recordsource = 表名
data1.refresh
在按鈕的click事件中加入
dim irow, icol as integer
dim irowcount, icolcount as integer
dim fieldlen() "存字段長度值
dim xlapp as excel.application
dim xlbook as excel.workbook
dim xlsheet as excel.worksheet
set xlapp = createobject("excel.application")
set xlbook = xlapp.workbooks.add
set xlsheet = xlbook.worksheets(1)
with data1.recordset.movelast
if .recordcount < 1 then
msgbox ("error 沒有記錄!")
exit sub
end if
irowcount = .recordcount "記錄總數
icolcount = .fields.count "字段總數
redim fieldlen(icolcount).movefirst
for irow = 1 to irowcount + 1
for icol = 1 to icolcount
select case irow
case 1 "在excel中的第一行加標題
xlsheet.cells(irow, icol).value = .fields(icol - 1).name
case 2 "將數組fieldlen()存為第一條記錄的字段長
if isnull(.fields(icol - 1)) = true then
fieldlen(icol) = lenb(.fields(icol - 1).name)
"如果字段值為null,則將數組filelen(icol)的值設為標題名的寬度
else
fieldlen(icol) = lenb(.fields(icol - 1))
end if
xlsheet.columns(icol).columnwidth = fieldlen(icol)
"excel列寬等于字段長
xlsheet.cells(irow, icol).value = .fields(icol - 1)
"向excel的cells中寫入字段值
case else
fieldlen1 = lenb(.fields(icol - 1))
if fieldlen(icol) < fieldlen1 then
xlsheet.columns(icol).columnwidth = fieldlen1
"表格列寬等于較長字段長
fieldlen(icol) = fieldlen1
"數組fieldlen(icol)中存放最大字段長度值
else
xlsheet.columns(icol).columnwidth = fieldlen(icol)
end if
xlsheet.cells(irow, icol).value = .fields(icol - 1)
end select
next
if irow <> 1 then
if not .eof then .movenext
end if
next
with xlsheet
.range(.cells(1, 1), .cells(1, icol - 1)).font.name = "黑體"
"設標題為黑體字
.range(.cells(1, 1), .cells(1, icol - 1)).font.bold = true
"標題字體加粗
.range(.cells(1, 1), .cells(irow, icol - 1)).borders.linestyle = xlcontinuous
"設表格邊框樣式
end with
xlapp.visible = true "顯示表格
xlbook.save "保存
set xlapp = nothing "交還控制給excel
end with
本程序在中文windows98、中文vb5下通過。