2016-09-28 55 views
1

我有一個DataGridView,我從多個excel文件導入數據。但是每次我輸入數據都會覆蓋以前的數據。我如何獲得它將下一個Excel文件添加到數據網格視圖中的前一個末尾?將多個數據源添加到datagridview vb.net

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 
+0

你不能擁有DGV的多個數據源 - 它是單數的。是我還是If和Else塊都做同樣的事情,除了一個有額外的DataTable變量 – Plutonix

+2

不是沒有,但你問了16個問題,並得到18個答案;只接受一個並且只投了一次。接受你認爲有用的答案和提升帖子有助於他人找到很好的答案。 [Tour]解釋它。如果源相同,則可以附加到數據表。 – Plutonix

回答

2

你可以簡單地填單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文件中的列數可以是不同的,但是如果有具有相同名稱的列,這些列的數據應該是相同類型的。

+1

我希望SQL能夠拼出所需的列,以確保'foo'將最終與foo列中的其他foos – Plutonix

+0

@Reza Ahaei儘管您的答案導入了數據,但它並不堆疊新的記錄在舊記錄的末尾。例如,我的第一次導入是100條記錄,而我的第二條導入是200條,那麼我的數據表中應該有300條記錄。 – Chrisetiquette

+0

@Chrisetiquette你將有300條記錄。 –