這是一個非常實(shí)用的例子,,它可以將你查詢出來的數(shù)據(jù)導(dǎo)出到Excel表格中,,具體步驟如下:
1,、這里使用的Access數(shù)據(jù)庫,,所以先建一個數(shù)據(jù)庫,這個數(shù)據(jù)庫要和工程文件和窗體文件放在同一個文件夾(所以建議先在某個磁盤下建一個文件夾),,數(shù)據(jù)庫的名字叫“學(xué)生.mdb”,,里面創(chuàng)建一個表叫“學(xué)生信息表”,表中有三個字段(學(xué)號,、姓名,、性別)。(當(dāng)然用SQL數(shù)據(jù)庫也可以,,你自己可以試一試) 2,、創(chuàng)建一個窗體,在窗體上添加一個datagrid控件(這個控件需要加載,,方法是:“工程”菜單——》“部件”——》“microsoft datagrid control 6.0(oledb)”選中前面的復(fù)選框,,打上對勾即可),然后到工具箱里面選中它,,在窗體上畫一個,;然后添加兩個按鈕,將第一個的caption改為“查詢”,,將第二個的caption改為“導(dǎo)出”,,再將第二個的enabled屬性改為false(這是因?yàn)橹挥心悴樵兊搅藬?shù)據(jù)才能導(dǎo)出,如果datagrid里沒有數(shù)據(jù),,是不能導(dǎo)出的) 3,、所有代碼如下: Option Explicit Dim i, j, k As Integer Dim xlapp As Variant Dim xlBook As Variant Dim xlSHEET As Variant Dim cn As New ADODB.Connection Dim rs As New ADODB.Recordset Private Sub Command1_Click() If rs.RecordCount <= 0 Then MsgBox "沒有可輸出的數(shù)據(jù),請選擇數(shù)據(jù)" Exit Sub Else Set xlapp = CreateObject("excel.application") Set xlBook = xlapp.workbooks.Add Set xlSHEET = xlBook.worksheets(1) xlapp.Visible = True On Error Resume Next If Err.Number <> 0 Then Set xlapp = CreateObject("Excel.Application") Set xlBook = xlapp.workbooks.Add Set xlSHEET = xlBook.ActiveSheet For k = 1 To DataGrid1.Columns.Count xlSHEET.Cells(1, k) = DataGrid1.Columns(k - 1).Caption Next k For i = 1 To rs.RecordCount + 1 For j = 0 To DataGrid1.Columns.Count xlSHEET.Cells(i + 1, j + 1) = rs(j) Next j rs.MoveNext Next i End If End Sub Private Sub Command2_Click() Set cn = Nothing Set rs = Nothing cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & App.Path & "\學(xué)生.mdb;Persist Security Info=False" rs.CursorLocation = adUseClient rs.Open "學(xué)生信息表", cn, adOpenDynamic, adLockOptimistic Set DataGrid1.DataSource = rs if rs.recordcount>0 then Command1.Enabled = True end if End Sub 4,、現(xiàn)在你就可以運(yùn)行了,,祝你好運(yùn) |
|