關於VBS串連MySQL與串連Excel,vbsmysqlexcel
目標:串連MySQL尋找資料放入建立Excel表
實現過程:
1.串連資料庫
首先要去MySQL官網下載個ODBC資料來源。
安裝之後,即可在控制台-管理工具-ODBC資料來源-添加,中看到MySQL驅動名稱:
'串連資料庫StrCnn="Provider=MSDASQL.1;Persist Security Info=True;Extended Properties='Driver=MySQL ODBC 5.3 Unicode Driver;SERVER=188.1.1.132;UID=grute;PWD=grute;DATABASE=grute;PORT=3307'"Set Cnn = CreateObject("ADODB.Connection")Cnn.Open strCnn'查看是否串連成功,成功狀態值為1If Cnn.State = 0 Then<span style="white-space:pre"></span>msgbox "串連資料庫失敗"<span style="white-space:pre"></span>wscript.quit End If
2.串連Excel
'串連Exceldim oExcel,oWb,oSheet Set oExcel= CreateObject("Excel.Application") oexcel.Workbooks.Add()
3.輸入SQL語句,從MySQL中尋找資料
strQuery = "select * from test"Set rs = Cnn.Execute(strQuery)
4.把MySQL的查詢結果迴圈放入Excel
<pre name="code" class="vb"><pre name="code" class="vb">'i為Excel行號,k為列號<pre name="code" class="vb">Dim ii=0arr_column = array("序號", "姓名", "使用者名稱", "密碼", "許可權")If Not rs.BOF ThenDo While Not rs.EOFi = i + 1For k = 1 To 5 '迴圈5次oExcel.Cells(i, k).Value = rs(arr_column(k - 1))Nextrs.MoveNextLoopElsewscript.echo "失敗"End If
5.儲存Excel
oexcel.ActiveWorkbook.SaveAs("C:\Users\Administrator\Desktop\test.xlsx")
6.退出
oExcel.WorkBooks.Close oExcel.Quit rs.CloseCnn.CloseSet Cnn = Nothingmsgbox "匯入完成"
以上,
完全代碼如下,要求本機安裝MySQL資料來源,且188.1.1.132機器上MySQL使用者名稱為grute、密碼為grute、庫名為grute、表名為test、test的列名分別為(序號,姓名,使用者名稱,密碼,許可權),儲存為尾碼名VBS即可運行。
'定義變數Dim CnnDim RstDim strCnnDim ii = 0arr_column = array("序號", "姓名", "使用者名稱", "密碼", "許可權")'串連資料庫StrCnn="Provider=MSDASQL.1;Persist Security Info=True;Extended Properties='Driver=MySQL ODBC 5.3 Unicode Driver;SERVER=188.1.1.132;UID=grute;PWD=grute;DATABASE=grute;PORT=3307'"Set Cnn = CreateObject("ADODB.Connection")Cnn.Open strCnn'查看是否串連成功,成功狀態值為1If Cnn.State = 0 Thenmsgbox "串連資料庫失敗"wscript.quit End If'串連Exceldim oExcel,oWb,oSheet Set oExcel= CreateObject("Excel.Application") oexcel.Workbooks.Add()'輸入SQL語句strQuery = "select * from test"Set rs = Cnn.Execute(strQuery)'i為Excel行號,k為列號arr_column = array("序號", "姓名", "使用者名稱", "密碼", "許可權")If Not rs.BOF ThenDo While Not rs.EOFi = i + 1For k = 1 To 5 '迴圈5次oExcel.Cells(i, k).Value = rs(arr_column(k - 1))Nextrs.MoveNextLoopElsewscript.echo "失敗"End Ifoexcel.ActiveWorkbook.SaveAs("C:\Users\Administrator\Desktop\test.xlsx")oExcel.WorkBooks.Close oExcel.Quit rs.CloseCnn.CloseSet Cnn = Nothingmsgbox "匯入完成"
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。