2010-04-29 79 views
1

我有这段代码来读取CVS文件。它读取每一行,用分隔符','分隔每行,并将字段值存储在数组'strline()'中。只阅读vb.net中CSV文件的特定字段

如何仅从CSV文件中提取必填字段?

例如,如果我有CSV文件等

类型,组编号,序列号,行号,日期(换行) 0,管理员,3,345678,1,26052010(换行) 1 ,工作人员,5,78654,3,26052010

I只需要列组的值,序列号和日期。

在此先感谢您的任何想法。

Dim myStream As StreamReader = Nothing 
    ' Hold the Parsed Data 
    Dim strlines() As String 
    Dim strline() As String 
    Try 
     myStream = File.OpenText(OpenFile.FileName) 
     If (myStream IsNot Nothing) Then 
     ' Hold the amount of lines already read in a 'counter-variable' 
     Dim placeholder As Integer = 0 
     strlines = myStream.ReadToEnd().Split(Environment.NewLine) 
     Do While strlines.Length <> -1 ' Is -1 when no data exists on the next line of the CSV file 
      strline = strlines(placeholder).Split(",") 
      placeholder += 1 
     Loop 
     End If 
    Catch ex As Exception 
     LogErrorException(ex) 

    Finally 

     If (myStream IsNot Nothing) Then 
     myStream.Close() 
     End If 
    End Try 

回答

7

1)请勿使用String.Split !!

CSV数据可以包含逗号,例如,

id,name 
1,foo 
2,"hans, bar" 

同样如上所述,你需要处理引号的字段等等...查看CSV Info了解更多详情。

2)退房TextFieldParser - 它摧毁了所有这些东西。

它将处理不同的逃逸你不能做string.split的无数......

样品来自:http://msdn.microsoft.com/en-us/library/cakac7e6.aspx

Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("C:\TestFolder\test.txt") 
    MyReader.TextFieldType = FileIO.FieldType.Delimited 
    MyReader.SetDelimiters(",") 
    Dim currentRow As String() 
    While Not MyReader.EndOfData 
     Try 
      currentRow = MyReader.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 

MyReader.ReadFields()部分将让你一个字符串数组,从那里,你需要使用索引等等

PK :-)

+1

+1 string.split不仅错误,与状态机 – 2010-04-29 22:06:51

+1

+1相比,速度更慢,用于在OP上标注重要警告。 – 2010-04-30 03:39:28

+0

我同意这是一个关于String.Split和“等等的一般性警告,但这一切都取决于数据来自何处以及规范是什么。大多数时候我已经读取了CSV文件并使用了String。分裂,如果我结束了太多的列,我没有通过文件,并告诉文件的制作者修复他的数据。 – 2010-04-30 07:30:26

0

也许而不只是进口选定字段,你应该导入一切,然后只使用你需要的。