2010-04-29 119 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

也許而不只是進口選定字段,你應該導入一切,然後只使用你需要的。