我在逐行读取semikolon分离的CSV文件时遇到问题。
看起来像这样:
标题 ID;名称;姓氏;街道;注释
。数据线 123;加里;米勒; Mystreet 123;"这是评论"
这是我的代码:
Set tsFile = cFiFo.FileSysObj.OpenTextFile(sCSVPath, ForReading)
While Not tsFile.AtEndOfStream
sLine = tsFile.ReadLine
sLine = Replace(sLine, """", "")
Call AddImportLine(sLine, iLinesErr, iLinesOK)
Wend
这是我在某些方面得到的(它主要起作用)。这条线路有些问题。我无法在文本编辑器或excel中看到换行符。
sLine 1的错误输出: 123;加里;米勒; Mystreet 123;这是
sLine 2输出错误: 评论
我该怎么办?
提前致谢
的Xyron
解决方案:
Set tsFile = cFiFo.FileSysObj.OpenTextFile(sCSVPath, ForReading)
sFile = tsFile.ReadAll
'Replacing all CarrigeReturn-LineFeeds with a placeholder (to make sure, that CarrigeReturn-LineFeeds being kept that way)
sFile = Replace(sFile, vbCrLf, "#^CRLF^#")
sFile = Replace(sFile, vbLf, "#^LF^#")
sFile = Replace(sFile, "#^CRLF^#", vbCrLf)
tsFile.Close
'Overwrite existing File
Set tsFile = cFiFo.FileSysObj.OpenTextFile(sCSVPath, ForWriting)
tsFile.Write (sFile)
tsFile.Close
'Reading
Set tsFile = cFiFo.FileSysObj.OpenTextFile(sCSVPath, ForReading)
While Not tsFile.AtEndOfStream
sLine = tsFile.ReadLine
sLine = Replace(sLine, """", "")
Call AddImportLine(sLine, iLinesErr, iLinesOK)
Wend
感谢您的大力帮助!
答案 0 :(得分:0)
如果您无法查找和删除导致问题的任何字符,您可以尝试手动清理。以下代码仅允许ASCII字符32到126,并且还删除双引号。
Dim ss() As String = System.IO.File.ReadAllLines(fileName)
For Each s As String In ss
Dim sb As StringBuilder = New StringBuilder
For Each c As Char In s
Dim i As Integer = CType(c,Integer)
If ((i >= 32) _
AndAlso ((i <= 126) _
AndAlso (i <> 34))) Then
sb.Append(c)
End If
Next
Dim sLine As String = sb.ToString
AddImportLine(sLine, iLinesErr, iLinesOK);
Next
如果ReadAllLines没有按照你想要的方式将你的行分成字符串,那么你可能会有一个流氓CR或换行符。您可以通过此示例ascii显示器运行文件的第一部分,以查看垃圾字符的ascii代码。
Private Sub DisplayFileAsAscii(ByVal fileName As String, ByVal numChars As Integer, ByVal includeText As Boolean)
Dim sb As StringBuilder = New StringBuilder
Dim MyFile As FileInfo = New FileInfo(fileName)
Dim sr As StreamReader = MyFile.OpenText
'Read a single character.
Dim FirstChar As Integer = sr.Read
While (FirstChar <> 0)
sb.Append(("[" + FirstChar.ToString))
If includeText Then
sb.Append(("~" + CType(FirstChar,Char).ToString))
End If
sb.Append("]")
FirstChar = sr.Read
numChars = (numChars - 1)
If (numChars < 0) Then
Exit While
End If
End While
MessageBox.Show(sb.ToString)
End Sub
答案 1 :(得分:0)
如果使用记事本将其复制并粘贴到wordpad中以检查换行符。记事本完全忽略并隐藏回车,但其他程序则没有。记事本仅查找换行符。
在记事本中,CR不可见时,需要按两次箭头键来移动文本插入符号。
如果从基于浏览器的文档(例如网页和帮助系统)进行处理,有时会将杂散的回车卡无形地插入记事本中。