Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:/book1.xls; Extended Properties=Excel 8.0;"
Try
Dim oleDbConnection As OleDbConnection = New OleDbConnection(sConnectionString)
oleDbConnection.Open()
'获取excel表
Dim dataTable As DataTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,Nothing)
'获取sheet名,其中(0)(1)...(N): 按名称排列的表单元素
Dim tableName As String = dataTable.Rows(0)(2).ToString().Trim()
tableName = "[" & tableName.Replace(" ' "," ") & "]"
Dim query As String = "SELECT c1,c2,c3 FROM " & tableName
Dim dataset As DataSet = New DataSet()
Dim oleAdapter As OleDbDataAdapter = New OleDbDataAdapter(query,sConnectionString)
oleAdapter.Fill(dataset,"Rwb")
'可读取EXCEL中的记录数
MessageBox.Show(dataset.Tables(0).Rows.Count)
Dim sqlcon As sqlClient.sqlConnection = New sqlClient.sqlConnection("Data Source=./sqlexpress;Initial Catalog=test;User ID=sa;Password=123")
sqlcon.Open()
'从excel文件获得数据后,插入记录到sql Server的数据表
Dim dataTable1 As DataTable = New DataTable()
Dim sqlDA1 As sqlClient.sqlDataAdapter = New sqlClient.sqlDataAdapter("SELECT c1,c3 from BOOK1 ",sqlcon)
Dim sqlCB1 As sqlClient.sqlCommandBuilder = New sqlClient.sqlCommandBuilder(sqlDA1)
sqlDA1.Fill(dataTable1)
Dim dataRow11 As DataRow
For Each dataRow11 In dataset.Tables("Rwb").Rows
'sql里数据dataRow1
Dim dataRow1 As DataRow = dataTable1.NewRow()
dataRow1("C1") = dataRow11("C1")
dataRow1("C2") = dataRow11("C2")
dataRow1("C3") = dataRow11("C3")
dataTable1.Rows.Add(dataRow1)
Next
MessageBox.Show("新插入 " & dataTable1.Rows.Count.ToString() & " 条记录 ")
sqlDA1.Update(dataTable1)
oleDbConnection.Close()
Catch ex As Exception
Console.WriteLine(ex.ToString())
End Try