[英]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.