如何将两个或多个Excel数据或文件导入Gridview

时间:2019-12-19 19:15:40

标签: excel vb.net

我想将两个或多个Excel文件导入GridView,但仅导入并读取第一个Excel文件,而不导入两个文件。如何导入更多Excel数据?

导入两个或更多Excel文件 enter image description here

导入2个或更多Excel文件 enter image description here

这是导入的示例:

            Dim conn As OleDbConnection
            Dim dta As OleDbDataAdapter
            Dim dts As DataSet
            Dim Excel As String
            Dim OpenFileDialog As New OpenFileDialog
            OpenFileDialog.InitialDirectory = "C:\Test"
            OpenFileDialog.Multiselect = True
            OpenFileDialog.Filter = "All Files (*.*)|*.*|Excel Files (*.xlsx)|*.xlsx|Xls Files (*.xls)|*.xls"
            If OpenFileDialog.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
                Dim fi As New IO.FileInfo(OpenFileDialog.FileName)
                Dim Filename As String = OpenFileDialog.FileName
                Excel = fi.FullName
                conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Excel + "; 
                Extended Properties=Excel 12.0;")
                dta = New OleDbDataAdapter("select * from [Sheet$]", conn)
                dts = New DataSet
                dta.Fill(dts, "[Sheet$]")
                GridControl1.DataSource = dts
                GridControl1.DataMember = "[Sheet$]"
                conn.Close()
            End If

是否可以将更多Excel文件导入GridView?

2 个答案:

答案 0 :(得分:0)

好的,所以我对您拥有的选项进行了快速阅读,并认为合并DataSet是正确的。因此,我使用注释中提到的@preciousbetine开头的FileNames()来获取所有选定的文件名。然后,我对获取的每个文件进行了简单合并。下面的代码示例:

.cpp

答案 1 :(得分:0)

您可能想在GetFiles中呼叫Form.Load,在DisplayNextFile中呼叫Button.Click

该代码创建文件列表,并使用索引字段跟踪下一个文件。在命令文本中,我将[Sheet$]更改为[Sheet1$]。 Sheet1是默认的工作表名称。如果您没有默认名称,或者有多个工作表,则必须扩展代码以检索每个文件中的工作表名称。

Using...End Using块可确保即使发生错误也可以关闭和处置数据库对象。在这种情况下,连接和命令都包含在一个块中(请注意“使用”第一行之后的逗号)。

Private files As New List(Of String)
Private index As Integer

Private Sub GetFiles()
    Dim OpenFileDialog1 As New OpenFileDialog
    OpenFileDialog1.InitialDirectory = "C:\Test"
    OpenFileDialog1.Multiselect = True
    OpenFileDialog1.Filter = "All Files (*.*)|*.*|Excel Files (*.xlsx)|*.xlsx|Xls Files (*.xls)|*.xls"
    If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
        files = OpenFileDialog1.FileNames.ToList
    End If
End Sub

Private Sub DisplayNextFile()
    If index > files.Count - 1 Then
        MessageBox.Show("The last file has been displayed")
        Return
    End If
    Dim dt As New DataTable
    Using conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & files(index) & "; Extended Properties=Excel 12.0;"),
            cmd As New OleDbCommand("select * from [Sheet1$]", conn)
        dt.Load(cmd.ExecuteReader)
    End Using
    DataGridView1.DataSource = dt
    index += 1
End Sub