2017-09-21 63 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的鏈接。 –

相關問題