1 Dim t 2 '獲取系統當前時間 3 t=Year(Now)&"."&Month(Now)&"."&Day(Now)&"-"&Hour(Now)&"."&Minute(Now)&"."&Second(Now) 4 Dim filename,sheetname ,xlApp, xlWorkbook, xlWorksheet 5 Dim i,constr,con,rst,iRowCount,sql 6 7 constr="Provider=SQLOLEDB.1;Password=pwd;Persist Security Info=True;User ID=userName;Initial Catalog=databaseName;Data Source=127.0.0.1" '如果是wincc在鏈接ip后面加 \wincc 8 Set con = CreateObject("ADODB.Connection") 9 con.ConnectionString = constr 10 con.Open 11 12 13 If Con.State = 0 Then '判斷數據庫連接是否成功 14 ' MsgBox "連接數據庫失敗" 15 Else 16 MsgBox "連接數據庫成功" 17 End If 18 '打開excel表 19 Set xlApp=CreateObject("Excel.Application") 20 Set xlWorkBook=xlApp.Workbooks.Add 21 xlApp.Visible=True 22 xlApp.Sheets.Item(1).Name="ERS點" '設置第一個sheet名字 23 Set xlWorksheet=xlApp.Sheets.Item(1) 24 '寫入列名字 25 xlWorksheet.Range("B1").Value ="X" 26 xlWorksheet.Range("C1").Value="Y" 27 xlWorksheet.Range("D1").Value="Z" 28 'xlWorksheet.Range("A1").Value="ID" 29 xlWorksheet.Range("A1").Value="點名" 30 xlWorksheet.Range("E1").Value="X1" 31 xlWorksheet.Range("F1").Value="Y1" 32 xlWorksheet.Range("G1").Value="Z1" 33 34 '查詢 35 Set rst= CreateObject("ADODB.Recordset") 36 sql="select * from initial_coordinates" 37 rst.open sql,con,1,3,1 38 iRowCount = rst.recordcount ‘統計查詢到的的數據量 39 'Msgbox iRowCount 40 '寫值到excel 41 For i=2 To iRowCount+1 42 xlWorksheet.Range("A" & i).Value= rst(1) 43 xlWorksheet.Range("B" & i).Value= rst(2) 44 xlWorksheet.Range("C" & i).Value= rst(3) 45 xlWorksheet.Range("D" & i).Value= rst(4) 46 xlWorksheet.Range("E" & i).Value= rst(5) 47 xlWorksheet.Range("F" & i).Value= rst(6) 48 xlWorksheet.Range("G" & i).Value= rst(7) 49 50 rst.movenext 51 Next 52 xlApp.ActiveWorkbook.SaveAs("d:\ERS點數據"+ t +".xls") 53 MsgBox "導出數據成功!" 54 If con.state Then con.Close '關閉數據連接 55 Set xlWorkBook=Nothing 56 Set xlApp=Nothing