解析固定宽度的.csv文件

时间:2015-01-19 08:33:52

标签: vb.net

我有.csv文件,我需要解析。它没有划分但是固定的,你告诉我什么是解析这种失败的最佳方法。这是样本:

Object Name  IP Address Name    NE ID   NE Type/Release Partition Access Profile    Supervision State   
MS-POLT01    10.45.3.11 MS-POLT01   1   7302 ISAM IHUB R4.3 defaultPAP  Supervised  
TPO-POLT02   10.34.1.33/10.74..61   TPO-POLT02  10  7302 ISAM IHUB R4.3 defaultPAP  Supervised  
WPU-POLT02   10.70.8.21 WPU-POLT02  100 7302 ISAM IHUB R4.3 defaultPAP  Supervised  
MOV-POLT01   10.70.2.45 MOV-POLT01  101 7302 ISAM IHUB R4.3 defaultPAP  Supervised  
Results of 'EROS': 6 records found. Duration 0 s.
This query was executed by john

编辑 - 供进一步讨论:

   Sub Main()

        Using MyReader As New Microsoft.VisualBasic.FileIO.
    TextFieldParser("file.csv")

            MyReader.TextFieldType =
                Microsoft.VisualBasic.FileIO.FieldType.Delimited
            MyReader.Delimiters = New String() {vbTab}
            Dim currentRow As String()
            'Loop through all of the fields in the file.  
            'If any lines are corrupt, report an error and continue parsing.  
            While Not MyReader.EndOfData
                Try
                    currentRow = MyReader.ReadFields()

                    ' Debug.Print(String.Join(",", currentRow))
                    For Each currentField In currentRow
                        Debug.Print(currentField)
                    Next
                    ' Include code here to handle the row. 


                Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                    Console.WriteLine("Line " & ex.Message & " is invalid.  Skipping")
                End Try
            End While
        End Using

        Console.ReadLine()

    End Sub

1 个答案:

答案 0 :(得分:2)

使用TextFieldParser-class,它是为此目的而准确开发的:

MSDN Example

Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\TestFolder\test.log")
   Reader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.FixedWidth
   Reader.SetFieldWidths(5, 10, 11, -1)
   Dim currentRow As String()
   While Not Reader.EndOfData
      Try
         currentRow = Reader.ReadFields()
         Dim currentField As String 
         For Each currentField In currentRow
            MsgBox(currentField)
         Next 
      Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
         MsgBox("Line " & ex.Message &
         "is not valid and will be skipped.")
      End Try 
   End While 
End Using