繁体   English   中英

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

[英]Adding multiple datasources to a datagridview vb.net

我有一个DataGridView ,我正在从多个Excel文件中将数据导入其中。 但是每次导入数据时,它都会覆盖以前的数据。 如何在数据网格视图中将下一个excel文件添加到上一个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文件中的列数可以不同,但​​是,如果存在具有相同名称的列,则这些列的数据应具有相同的类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM