我有这段代码来读取CVS文件.它读取每一行,用分隔符','分隔每一行,并将字段值存储在数组'strline()'中.
如何仅从CSV文件中提取必填字段?
例如,如果我有像这样的CSV文件
类型,组,否,序列号,行号,日期(换行符)0,管理员,3,345678,1,26052010(换行符)1,员工,5,78654,3,26052010
我只需要列Group,Sequence No和date的值.
提前感谢任何想法.
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
Run Code Online (Sandbox Code Playgroud)
1)不要使用String.Split
!!
CSV数据可以包含逗号,例如
id,name
1,foo
2,"hans, bar"
Run Code Online (Sandbox Code Playgroud)
同样如上所述,您需要处理引用的字段等...有关详细信息,请参阅CSV信息.
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
Run Code Online (Sandbox Code Playgroud)
该MyReader.ReadFields()
部分将为您提供一系列字符串,从那里您将需要使用索引等...
PK :-)
归档时间: |
|
查看次数: |
7930 次 |
最近记录: |