如何用Excel读取数据并将其保存到数据库中
如果您正在寻找一种简单的方法来将Excel中的数据转移到数据库中,您来对地方了。本文将介绍如何使用VBA调用ADO对象将Excel数据导出到数据库中。首先,我们需要在Excel中打开Visual Basic Editor,然后将以下代码复制到模块中:
Sub ExportToDatabase()
Dim cn As ADODB.Connection
Set cn = New ADODB.Connection
cn.ConnectionString = "Provider=SQLOLEDB;Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;"
cn.Open
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "SELECT * FROM myTable", cn, adOpenKeyset, adLockOptimistic, adCmdText
'Loop through the rows in the worksheet
Dim iRow As Integer
For iRow = 2 To Range("A1").End(xlDown).Row
'Add a new record to the recordset
rs.AddNew
'For each field in the recordset
rs.Fields("ID").Value = Range("A" & iRow).Value
rs.Fields("Name").Value = Range("B" & iRow).Value
rs.Fields("Quantity").Value = Range("C" & iRow).Value
rs.Fields("Price").Value = Range("D" & iRow).Value
'Update the recordset
rs.Update
Next iRow
'Close the recordset and the connection
rs.Close
cn.Close
End Sub
这段代码将数据从Excel中读取并添加到名为“myTable”的数据库表中。您需要根据自己的情况修改该代码并更改连接字符串中的服务器地址、数据库名称、用户名和密码。完成后,请按F5运行代码即可将数据从Excel导入到数据库中。
下载地址
用户评论