我需要创建一个新的 CSV 文件。编写我自己的例程不会是一项艰巨的任务,但是基类库中有一个例程吗?
问问题
3833 次
2 回答
7
这是可用于从字符串列表生成一行 CSV 文件的函数(也可以使用 IEnumerable(Of String) 或字符串数组):
Function CreateCSVRow(strArray As List(Of String)) As String
Dim csvCols As New List(Of String)
Dim csvValue As String
Dim needQuotes As Boolean
For i As Integer = 0 To strArray.Count() - 1
csvValue = strArray(i)
needQuotes = (csvValue.IndexOf(",", StringComparison.InvariantCulture) >= 0 _
OrElse csvValue.IndexOf("""", StringComparison.InvariantCulture) >= 0 _
OrElse csvValue.IndexOf(vbCrLf, StringComparison.InvariantCulture) >= 0 _
OrElse csvValue.IndexOf(" ", StringComparison.InvariantCulture) = 0 _
OrElse csvValue.IndexOf(" ", StringComparison.InvariantCulture) = csvValue.Length-1)
csvValue = csvValue.Replace("""", """""")
csvCols.Add(If(needQuotes, """" & csvValue & """", csvValue))
Next
Return String.Join(",", csvCols.ToArray())
End Function
于 2013-11-19T17:32:30.857 回答
5
不在框架里,代码太简单了。使用 StreamWriter.Write() 轻松完成,您只需要做一点提升即可正确引用字符串。它只需要几行:
Module CsvWriter
Public Sub WriteCsvLine(ByVal out As System.IO.TextWriter, ByVal ParamArray Values() As Object)
For ix As Integer = 0 To Values.Length - 1
If ix > 0 Then out.Write(",")
If TypeOf (Values(ix)) Is String Then
out.Write("""" + CStr(Values(ix)).Replace("""", """""") + """")
Else
out.Write(Values(ix).ToString())
End If
Next
out.WriteLine()
End Sub
End Module
于 2012-10-18T20:46:38.293 回答