gpt4 book ai didi

.net - 将多个数据源添加到 datagridview vb.net

转载 作者:行者123 更新时间:2023-12-04 20:05:55 29 4
gpt4 key购买 nike

我有一个 DataGridView我正在从多个 excel 文件中导入数据。但是每次我导入数据时,它都会覆盖以前的数据。如何在数据 GridView 中将下一个 excel 文件添加到上一个文件的末尾?

If DataGridView1.RowCount > 0 Then
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\Work\4pc_test1.xlsx;Extended Properties=Excel 12.0;")

'MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fd.FileName & "';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "Net-informations.com")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)

'DataGridView1.DataSource = DtSet.Tables(0)

Dim tab As DataTable = DtSet.Tables(0)
DataGridView1.DataSource = tab

MyConnection.Close()
Else

'The below connection allows for the opening of .xls files and .xlsx. The one reamed out below doesnt open up .xls files.
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\Work\4pc_test1.xlsx;Extended Properties=Excel 12.0;")

'MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & fd.FileName & "';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection)
MyCommand.TableMappings.Add("Table", "Net-informations.com")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
DataGridView1.DataSource = DtSet.Tables(0)

MyConnection.Close()
End If

最佳答案

您可以简单地填写一个 DataTable多次和行将添加到 DataTable这边走。例如:

Try
Dim table = New DataTable()
Dim connection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=D:\excel1.xlsx;" & _
"Extended Properties=Excel 12.0;"
Using adapter As New OleDbDataAdapter("select * from [Sheet1$]", connection)
adapter.Fill(table)
End Using
connection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=D:\excel2.xlsx;" & _
"Extended Properties=Excel 12.0;"
Using adapter As New OleDbDataAdapter("select * from [Sheet1$]", connection)
adapter.Fill(table)
End Using
Me.DataGridView1.DataSource = table
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try

不同的excel文件中的列数可以不同,但​​是如果有同名的列,那么这些列的数据应该是相同类型的。

关于.net - 将多个数据源添加到 datagridview vb.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39758766/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com