VB .NET把Excel中的資料匯入SQL SERVER資料庫
其實不算原創,論壇裡有人發的,我正好專案寫到這裡,缺的語句較多,無法執行,我補充了一下,可以簡單的運行了,測試了一下,速度還不錯。
VS2015可用,自己新增窗體和控制元件吧,只需要一個OpenFileDialog和Button,預設檔案中帶有欄位名。
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.ClickTry
Dim fileName As String
OpenFileDialog1.ShowDialog()
fileName = OpenFileDialog1.FileName
'建立EXCEL連線,讀入資料,支援 Microsoft Excel 2010
Dim strConn As String = "Provider= Microsoft.Ace.OleDb.12.0;Data Source='" & fileName & "';Extended Properties=Excel 12.0;"
'建立EXCEL連線,讀入資料,支援 Microsoft Excel 2003
'Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fileName & "';Extended Properties=Excel 8.0;"
Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn)
Dim ds As DataSet = New DataSet
da.Fill(ds, "自己的資料表")
Me.DataGridView1.DataSource = ds.Tables(0)
If ds.Tables(0).Rows.Count > 0 Then
Dim strSql As String
Dim CnnStr As String = "server=localhost;database=自己的資料庫;user id=sa;password=密碼"
Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(CnnStr)
conn.Open()
Dim myCmd As SqlClient.SqlCommand
Dim i As Integer
For i = 0 To ds.Tables(0).Rows.Count - 1 Step i + 1
'根據自己的欄位新增
strSql = "insert into 登入表 VALUES ('" + ds.Tables(0).Rows(i).Item(0).ToString + "','" +
ds.Tables(0).Rows(i).Item(1).ToString + "','" + ds.Tables(0).Rows(i).Item(2).ToString + "','" +
ds.Tables(0).Rows(i).Item(3).ToString + "')"
Application.DoEvents()
myCmd = New SqlClient.SqlCommand(strSql, conn)
myCmd.ExecuteNonQuery()
Next
MsgBox("匯入儲存成功!", 48, "提示")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub