VB.NET将EXCEL中的数据导入到SQL SERVER

前端之家收集整理的这篇文章主要介绍了VB.NET将EXCEL中的数据导入到SQL SERVER前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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(" ' "," ") & "]"

'利用sql语句从Excel文件获取数据

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)

'sql数据库连接

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

原文链接:https://www.f2er.com/vb/261568.html

猜你在找的VB相关文章