top
Loading...
用VB控制EXCEL生成報表
做為一種簡捷、系統的 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 $#@60; 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
Fiel n(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) $#@60; 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 $#@60;$#@62; 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下通過。
作者:http://www.zhujiangroad.com
來源:http://www.zhujiangroad.com
北斗有巢氏 有巢氏北斗