只读取csv中的某些列

时间:2014-10-17 11:59:54

标签: vb.net csv export-to-csv text-parsing

所以我有一个csv文件,里面有额外的逗号。我知道在特定专栏之后我不需要任何东西。所以基本上在第12栏之后的任何信息我都不需要。我不会对csv看到它时的样子有发言权,所以我无法在那里改变它。我想知道是否有办法只读取前12列并忽略其余的csv文件。

这就是代码现在的样子。

感谢您的帮助

Private Sub GetData(ByVal Path As String, ByRef DG As DataGridView, Optional ByVal NoHeader As Boolean = False)
    Dim Fields(100) As String
    Dim Start As Integer = 1
    If NoHeader Then Start = 0
    If Not File.Exists(Path) Then
        Return
    End If
    Dim Lines() As String = File.ReadAllLines(Path)
    Lines(0) = Lines(0).Replace(Chr(34), "")
    Fields = Lines(0).Split(",")
    If NoHeader Then
        For I = 1 To Fields.Count - 1
            Fields(I) = Str(I)
        Next
    End If

    dt = New DataTable()

    For Each Header As String In Fields
        dt.Columns.Add(New DataColumn(Header.Trim()))
        Dim desiredSize As Integer = 11

        While dt.Columns.Count > desiredSize
            dt.Columns.RemoveAt(desiredSize)
        End While

    Next
    For I = Start To Lines.Count - 1
        Lines(I) = Lines(I).Replace(Chr(34), "")
        Fields = Lines(I).Split(",")

        Dim dr As DataRow = dt.Rows.Add()
        For j = 0 To Fields.Count - 1
            dr(j) = Fields(j).Trim()
        Next

    Next

    DG.DataSource = dt
End Sub

1 个答案:

答案 0 :(得分:1)

您真正需要做的就是在for循环中迭代Fields的for循环中,将For j = 0 to Fields.Count - 1替换为For j = 0 to 11