我正在使用 asp.Net MVC 应用程序将 Excel 数据从 CSV 表单上传到数据库。使用流读取器读取 csv 文件时,如果行包含小写字母后跟大写字母,则会分成两行。例如。
Line :"1,This is nothing but the Example to explanationIt results wrong, testing example"
This line splits to :
Line 1: 1,This is nothing but the Example to explanation"
Line 2:""
Line 3:It results wrong, testing example
其中 CSV 文件生成正确的“”1,这只是解释的示例结果错误,测试示例“
code :
Dim csvFileReader As New StreamReader("my csv file Path")
While Not csvFileReader.EndOfStream()
Dim _line = csvFileReader.ReadLine()
End While
为什么会发生这种情况?如何解决这个问题。
最佳答案
当 Excel 电子表格中的单元格包含多行并将其保存到 CSV 文件时,Excel 使用换行符(ASCII 值 0x0A)分隔单元格中的行。电子表格中的每一行都用典型的回车/换行对 (0x0D 0x0A) 分隔。当您在记事本中打开 CSV 文件时,它根本不显示单独的 LF 字符,因此看起来它们都在一行上运行。因此,在 CSV 文件中,即使记事本没有显示它,它实际上看起来像这样:
' 1,"This is nothing but the Example to explanation{LF}It results wrong",testing example{CR}{LF}
根据MSDN documentation在 StreamReader.Readline
方法上:
A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r"), or a carriage return immediately followed by a line feed ("\r\n").
因此,当您调用ReadLine
时,它将在多行单元格中的第一行末尾停止读取。为了避免这种情况,您需要使用不同的“读取”方法,然后按 CR/LF 对进行拆分,而不是单独进行拆分。
但是,这并不是您在读取 CSV 文件时遇到的唯一问题。例如,您还需要正确处理 CSV 中单元格中引号字符的转义方式。在这种情况下,除非确实有必要以自己的方式实现,否则最好使用现有的库来读取文件。在这种情况下,Microsoft 在 .NET 框架中提供了一个类,可以正确处理读取 CSV 文件(包括具有多行单元格的文件)。该类的名称为 TextFieldParser
,位于 Microsoft.VisualBasic.FileIO
命名空间中。以下是 MSDN 中页面的链接,该页面解释了如何使用它来读取 CSV 文件:
http://msdn.microsoft.com/en-us/library/cakac7e6
这是一个例子:
Using reader As New TextFieldParser("my csv file Path")
reader.TextFieldType = FieldType.Delimited
reader.SetDelimiters(",")
While Not reader.EndOfData
Try
Dim fields() as String = reader.ReadFields()
' Process fields in this row ...
Catch ex As MalformedLineException
' Handle exception ...
End Try
End While
End Using
关于vb.net - 如何: streamreader in csv file splits to next if lowercase followed by uppercase in line,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11721346/