[英]How to export Excel data from different sheets to SQL-SERVER Database?
我是 Excel VBA 和 SQL 的新手。 我設法創建了一個宏按鈕並將 Excel 單元格數據推送到 SQL 服務器表。 不過,我有點不解:
如何從不同的工作表中獲取 Excel 單元格數據,然后將它們推送到 SQL Server 數據庫中的不同表中? (目前,我在一個 Excel 文件中有 3 張紙 - 客戶、測試、信息。)
當前工作代碼:
Sub Button1_Click()
Dim conn As New ADODB.Connection
Dim iRowNo As Integer
Dim sCustomerId, sFirstName, sLastName As String
With Sheets("Customers")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=TESTpc\SQLEXPRESS;Initial Catalog=ExcelSQLServerDemo;Trusted_connection=yes"
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
sCustomerId = .Cells(iRowNo, 1)
sFirstName = .Cells(iRowNo, 2)
sLastName = .Cells(iRowNo, 3)
'Generate and execute sql statement to import the excel rows to SQL Server table
conn.Execute "INSERT into dbo.Customers (CustomerId, FirstName, LastName) values ('" & sCustomerId & "', '" & sFirstName & "', '" & sLastName & "')"
iRowNo = iRowNo + 1
Loop
MsgBox "Customers Exported To Database"
conn.Close
Set conn = Nothing
End With
End Sub
我是否需要將數據存儲在數組中,然后將它們推送到數據庫?
您不應該對要導出的每一行都使用插入查詢。 相反,如果您想手動執行此操作,請打開一個記錄集:
Sub Button1_Click()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim iRowNo As Integer
Dim sCustomerId, sFirstName, sLastName As String
With Sheets("Customers")
'Open a connection to SQL Server
conn.Open "Provider=SQLOLEDB;Data Source=TESTpc\SQLEXPRESS;Initial Catalog=ExcelSQLServerDemo;Trusted_connection=yes"
conn.CursorLocation = adUseClient 'Use a client-side cursor
rs.Open "SELECT * FROM dbo.Customers", conn, adOpenDynamic, adLockOptimistic 'Open the table into a recordset
'Skip the header row
iRowNo = 2
'Loop until empty cell in CustomerId
Do Until .Cells(iRowNo, 1) = ""
rs.AddNew 'Add a new row
rs!CustomerId = .Cells(iRowNo, 1) 'Set row values
rs!FirstName = .Cells(iRowNo, 2)
rs!LastName = .Cells(iRowNo, 3)
rs.Update 'Commit changes to database, you can try running this once, or once every X rows
iRowNo = iRowNo + 1
Loop
MsgBox "Customers Exported To Database"
conn.Close
Set conn = Nothing
End With
End Sub
這有幾個優點,包括但不限於提高性能、插入引用值的能力和提高穩定性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.