仅从 vb.net 中的 CSV 文件读取特定字段 [英] Read only particular fields from CSV File in vb.net
问题描述
我有这个代码来读取 CVS 文件.它读取每一行,通过分隔符 ',' 划分每一行,并将字段值存储在数组 'strline()' 中.
I have this code to read a CVS file. It reads each line, devides each line by delimiter ',' and stored the field values in array 'strline()' .
如何仅从 CSV 文件中提取必填字段?
How do I extract only required fields from the CSV file?
例如,如果我有一个像 CSV 文件
For example if I have a CSV File like
类型、组、编号、序列号、行号、日期(换行)0,Admin,3,345678,1,26052010 (换行)1,员工,5,78654,3,26052010
Type,Group,No,Sequence No,Row No,Date (newline) 0,Admin,3,345678,1,26052010 (newline) 1,Staff,5,78654,3,26052010
我只需要列组、序列号和日期的值.
I Need only the value of columns Group,Sequence No and date.
提前感谢您的任何想法.
Thanks in advance for any ideas.
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
推荐答案
1) DO NOT USE String.Split
!!
1) DO NOT USE String.Split
!!
CSV 数据可以包含逗号,例如
CSV data can contain comma's, e.g.
id,name
1,foo
2,"hans, bar"
同样如上所述,您需要处理引用的字段等...参见 CSV 信息 了解更多详情.
Also as above you would need to handle quoted fields etc... See CSV Info for more details.
2) 查看 TextFieldParser -它处理所有这类事情.
2) Check out TextFieldParser - it hadles all this sort of thing.
它将处理无数不同的转义,你不能用 string.split...
It will handle the myriad of different escapes you can't do with 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()
部分将为您提供一个字符串数组,从那里您需要使用索引等...
The MyReader.ReadFields()
part will get you an array of strings, from there you'll need to use the index etc...
PK :-)
这篇关于仅从 vb.net 中的 CSV 文件读取特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!