在其字段内使用LineFeeds读取Csv文件 [英] Read Csv file with LineFeeds within its fields
问题描述
我有这段代码可以读取csv文件:
I have this code to read a csv file :
Dim strLineValue As String
Using sr As StreamReader = File.OpenText("FilePath")
strLineValue = sr.ReadLine
Do While strLineValue IsNot Nothing
strLineValue = sr.ReadLine
n += 1
Loop
End Using
我的问题是我遇到了如下这样的csv文件:
My problem is that I come across a csv file that the lines is like this:
"Text1 LF LF text2","text3",text4,text5, , , , ,LF
"Text6 LF LF text8","text9",text10,text11, , , , ,LF
其中LF是换行符.
所以我得到这样的东西是错误的
So I get something like this which is wrong
Text1
text2 text3 text4 text5
Text6
text8 text9 text10 text11
任何想法如何克服此类文件中代码的这种错误行为
Any ideas how I can overcome this wrong behaviour of my code in this type of files
PS. 1.如果我在excel中打开csv文件,它可以正确识别行,则它只有一个多行第一个单元格
2.我在想,也许前2个LF只是LF,而我在每行末尾的LF是LF和CR,但是我如何看清差异(我在Word中打开了csv文件以查看字符)
PS. 1.If I open the csv file in excel it recognises the lines properly , it just have a multiline first cell
2. I am thinking that maybe the first 2 LF are just LF and the LF that I have in the end of each line are LF and CR but how I can see the difference (I opened the csv file in the Word to see the characters)
推荐答案
您有一些用双引号括起来的字段-"
.在CSV文件中,通常表示您应该使用整个字段而不是对其进行解析.
You have some fields that are enclosed in double-quotes - "
. In CSV files, that usually indicates that you're supposed to take the whole field and not parse it.
使用 Microsoft确实很容易做到. VisualBasic.FielIO.TextFieldParser 类.这是一个示例:
This is really easy to do with the Microsoft.VisualBasic.FielIO.TextFieldParser class. Here's an example:
Imports Microsoft.VisualBasic.FileIO
Dim parser As TextFieldParser = New TextFieldParser("TestFile.txt")
parser.Delimiters = New String() {","}
parser.HasFieldsEnclosedInQuotes = True
While Not parser.EndOfData
Dim fields As String() = parser.ReadFields()
End While
这会将换行符保留在带引号的字段中:
This will preserve the line feeds in the quoted fields:
"Text1 LF LF text2" "text3" "text"4 "text5" blank blank blank blank blank
这篇关于在其字段内使用LineFeeds读取Csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!