2017-09-21 55 views
2

我需要将.txt文件导入到DataGridView中,每列由空格分隔,但问题出在最后一列。最后一列包含不应被评估为“分割”的空格(见下文)。将.txt导入到DataGridView(14列用空格分隔)VB.NET

' 1 2 3 4 5 6 7 8 9 10 11 12 13 14 SAT 0901 133000 1330 0002 002 003 000030 000000 00000000 000 00000C174BB 0000 This One

Private Sub ImpData(ByRef selectedFile As String) 
    Dim dt As New DataTable 
    For d = 1 To 14 
     dt.Columns.Add(d, GetType(String)) 
    Next 
    Dim lines = IO.File.ReadAllLines(selectedFile) 
    Dim colCount = 14 

    For Each line In lines 
     Dim objFields = From field In line.Split(" "c) 
         Select field 
     Dim newRow = dt.Rows.Add() 
     newRow.ItemArray = objFields.ToArray() 
    Next 
    DataGridView1.DataSource = dt 

End Sub 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MetroButton1.Click 

    Dim selectedfile As String = "" 
    OpenFileDialog1.ShowDialog() 
    selectedfile = Path.GetFullPath(OpenFileDialog1.FileName) 
    txtTEST1.Text = selectedfile 
    ImpData(selectedfile) 
End Sub 

“输入阵列比列在这个表中的号码更长。”是由于每行的最后一列引发错误。任何帮助将不胜感激。谢谢

+0

按列1至固定长度的13字符串? –

+0

是的。列1至13的长度固定,列14或多或少是描述列。 –

回答

1

以下代码正在为我工​​作,作为一种可能的解决方案。请注意,这是编码快速和肮脏。请看看OOP,例如Object Oriented Programming By Example

Private Sub ImpData(ByRef selectedFile As String) 
    Dim dt As New DataTable 
    For d = 1 To 14 
    dt.Columns.Add(d, GetType(String)) 
    Next 
    Dim lines = IO.File.ReadAllLines(selectedFile) 
    '-- Dim colCount = 16 

    For Each line In lines 
    Dim sLinePart1 As String = line.Substring(0, 77) 
    Dim sLinePart2 As String = line.Substring(78, line.Length - 78) 
    Dim objFields = From field In sLinePart1.Split(" "c) Select field 
    Dim newRow = dt.Rows.Add() 
    newRow.ItemArray = objFields.ToArray() 
    newRow(13) = sLinePart2 
    Next 
    DataGridView1.DataSource = dt 

End Sub 

请注意我没有两行空格。

SAT 0901 133000 1330 0002 002 003 000030 000000 00000000 000 00000C174BB 0000 This One first 
SAT 0901 133000 1330 0002 002 003 000030 000000 00000000 000 00000C174BB 0000 This One second 

enter image description here

+0

非常感谢!完美地满足我需要的东西。 –

+0

不用客气 - 为你添加了一个OOP的链接。 –

相关问题