如何将Excel数据从不同的工作表导出到SQL-SERVER数据库?

时间:2018-09-05 09:48:30

标签: sql excel database vba excel-vba

我是EXCEL-VBA和SQL的新手。我已经设法创建marco按钮并将excel单元格数据推送到SQL Server表。但是,我有点困惑:
问:如何从不同的工作表中获取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
问:是吗,我需要将数据存储在数组中,然后将其推送到数据库中?

非常感谢。

2 个答案:

答案 0 :(得分:1)

不应对要导出的每一行都使用插入查询。相反,如果要手动执行操作,请打开一个记录集:

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

这具有几个优点,包括但不限于提高性能,插入引用值的能力和提高的稳定性。

答案 1 :(得分:0)

使用 Sql Server导入和导出64位或32位数据

步骤1:screenshot1

第2步:Screenshot2

步骤3:Screenshot3

第4步:Screenshot4

第5步:Screenshot5

按照后续步骤