2

我有这个代码来读取一个 csv 文件:

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 文件,其中的行是这样的:

 "Text1 LF LF text2","text3",text4,text5, , , , ,LF 
 "Text6 LF LF text8","text9",text10,text11, , , , ,LF 

其中 LF 是换行符。

所以我得到了这样的错误

Text1

text2    text3    text4    text5
Text6

text8    text9    text10   text11

有什么想法可以克服我的代码在此类文件中的这种错误行为

PS。1.如果我在 excel 中打开 csv 文件,它可以正确识别行,它只有一个多行第一个单元格
2。我在想前 2 个 LF 可能只是 LF,而我在每行末尾的 LF 是LF 和 CR,但我怎么能看到差异(我在 Word 中打开了 csv 文件以查看字符)

4

2 回答 2

2

您有一些用双引号括起来的字段 - "。在 CSV 文件中,这通常表明您应该获取整个字段而不是解析它。

使用Microsoft.VisualBasic.FielIO.TextFieldParser类很容易做到这一点。这是一个例子:

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

这将保留引用字段中的换行符:

"Text1 LF LF text2" "text3" "text"4 "text5" blank blank blank blank blank
于 2013-08-13T10:36:47.570 回答
0

我会尝试;

strLineValue = strLineValue.replace(vblf,"")

并且看到它确实在行尾有一个 CR ......

您可以在 HEX 编辑器中看到差异,lf = 10 和 cr=13

chr(10) & chr(13) = vbcrlf
于 2013-08-13T10:33:04.727 回答