问题描述
我正在使用VB读取一些我认为来自Excel的.csv文件.有些行具有换行(LF),而有些行有回车和换行.我认为LF本身就是通过在Excel单元格中按Shift-Enter来获得 转到下一行.一个影响标题行的示例:
Im using VB to read some .csv files which I think have come out of Excel. Some of the lines have a Line Feed (LF) and some have both Carriage REturn and Line Feeds. I think the LF on their own is from hitting Shift-Enter in an Excel cell to get to the next line. An example which affects the title row:
名称,地址,移动电话< LF>
Name,Address,Mobile<LF>
电话号码,家庭< LF>
phone number, home<LF>
电话号码,镇,国家/地区
phone number, town, Country<CR>
John Smoth,伦敦,英国伦敦0712345678,020374635
John Smoth, London, 0712345678,020374635,London,UK<CR>
英国曼彻斯特的鲍勃·史密斯(Bob Smith),英国曼彻斯特的0712345678,0161746353< CR>
Bob Smith, Manchester,0712345678,0161746353,Manchester,UK<CR>
我要做的是找到LF,并在读取文件时忽略它们,以创建适当的"标题行.有什么想法可以实现吗?
What I want to do is find the LFs and ignore them while reading in the file, to create a 'proper' title row. Any ideas how this can be achieved??
推荐答案
您可能要考虑使用 TextFieldParser .
You might want to consider using a TextFieldParser for this.
Private Sub GetCSVData(ByVal filePath As String)
If Not String.IsNullOrWhiteSpace(filePath) Then
Try
Dim fi As New IO.FileInfo(filePath)
If fi.Exists Then
Using tfp As New Microsoft.VisualBasic.FileIO.TextFieldParser(fi.FullName)
With tfp
.TextFieldType = FileIO.FieldType.Delimited
.Delimiters = New String() {","}
' Set the following to true if you have fields
' which are enclosed in quotation marks:
.HasFieldsEnclosedInQuotes = False
End With
Dim currentLineOfText() As String
While Not tfp.EndOfData
currentLineOfText = tfp.ReadFields()
Stop
End While
End Using
End If
Catch ex As Exception
MessageBox.Show(String.Format("An error occurred:{0}{0}{1}", _
vbCrLf, ex.Message), _
"Error Reading Text File", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
End Try
End If
End Sub
默认情况下,它将跳过空行.
By default it will skip empty lines.
这篇关于读取.csv文件并遇到换行(LR)和回车(CR)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!