Excel數據批量導入到SqlServer的方法


1,以Excel為數據源建立連接導入。

關鍵點在於Excel的數據要有表頭,表頭要和數據庫表的列名一樣。連接字符串中HDR=YES不能省略,也就是第一行是表頭的意思。IMEX=1;是把數據都當作字符串讀取。

Sub test()
     
    Dim cn As ADODB.Connection
    Dim strSQL As String
    Dim lngRecsAff As Long
    Dim Headers As Boolean
    Dim strConn As String
    Dim path As String
    
    On Error GoTo test_Error
    
    Headers = True
    path = "c:\20131212.xls"
    strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
              "Data Source=" & path & ";" & _
              "Extended Properties=""Excel 8.0; IMEX=1;HDR=YES"""
                  
    Debug.Print strConn
    Set cn = New ADODB.Connection
    cn.Open strConn
     
     'Import by using Jet Provider.
    strSQL = "Insert INTO [odbc;Driver={SQL Server};" & _
             "Server=192.168.6.111;Database=answer;" & _
             "UID=sa;PWD=password].test1 " & _
             "Select * FROM [Sheet1$]"
    Debug.Print strSQL
    cn.Execute strSQL, lngRecsAff
    Debug.Print "Records affected: " & lngRecsAff
     
    cn.Close
    Set cn = Nothing
     
    On Error GoTo 0
    Exit Sub
     
test_Error:
     
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure test of VBA Document ThisWorkbook"
     
End Sub

 2,還有一種方案,是以sqlserver為數據源,寫法大致如下

 "INSERT INTO [檔案1] SELECT * FROM [Excel 8.0;Database=" & ThisWorkbook.FullName & ";HDR=YES].[sheet1$" & addr & "];"


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM