我使用的是Visual Basic,并且编程知识有限。我有一个文本框,包含四个txt或CSV文件的路径。我想将所有这些文件的数据导入DataGridView。我知道如何导入单个文件的数据,但不知道如何从多个文件导入数据。任何人都可以通过共享代码来帮助我。
答案 0 :(得分:0)
我确实回复了另一篇帖子,在这里重新加载以获取您的信息,希望可以提供帮助
注意:您需要将您的Datagridview标题文本与CSV文件中的标题匹配,以便在加载文件时更准确。
Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As System.EventArgs)Handles Button1.Click
OpenFileDialog1.InitialDirectory = "c:\temp\"
OpenFileDialog1.Filter = "CSV files (*.csv)|*.CSV"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
Me.OpenFileDialog1.Multiselect = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
For x = 0 To OpenFileDialog1.FileNames.Count
Try
Dim fName As String = ""
fName = OpenFileDialog1.FileNames(x)
Me.TextBox1.Text += fName
Dim TextLine As String = ""
Dim SplitLine() As String
If System.IO.File.Exists(fName) = True Then
Dim objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, "|")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If
Catch ex As Exception
End Try
Next
MsgBox("Total files loaded = " & OpenFileDialog1.FileNames.Count)
End If
End Sub