当在MS Excel中查看时导出为CSV问题时出现VB .Net

我遇到了一些非常奇怪的事情。 当导出为CSV时,我的顶行显示了引号,而下面的行显示了引号。

我使用UTF8编码并手动将双引号添加到该值,以便用引号括起来。

正在使用的代码是

Dim fs As New IO.FileStream(GenericValueEditorExportFilename.Value, IO.FileMode.Create) Dim writer As New IO.StreamWriter(fs, Encoding.UTF8) fs.Write(Encoding.UTF8.GetPreamble(), 0, Encoding.UTF8.GetPreamble().Length) .... .... .... While reader.Read If reader("TargetLanguageID") = targetLanguageID Then writer.WriteLine(Encode(reader("SourcePhrase")) & ", " & Encode(reader("TargetPhrase"))) End If .... .... .... Friend Shared Function Encode(ByVal value As String) As String Return ControlChars.Quote & value.Replace("""", """""") & ControlChars.Quote End Function 

显示在excel中的结果显示为( https://ibb.co/ntMYdw )

当我在Notepad ++中打开文件时,文本显示如下。 但每行显示不同。 为什么第一行显示它们,第二行没有。 Notepad ++结果显示为( https://ibb.co/fMkWWG )

Excel将第一行视为标题。

https://stackoverflow.com/a/24923167/2319909

所以这个问题是由BOM创build的,手动设置文件的编码作为写入文件的开始。

 fs.Write(Encoding.UTF8.GetPreamble(), 0, Encoding.UTF8.GetPreamble().Length) 

删除这个问题可以解决问题,文件保持在所需的UTF8编码,因为它在stream编写器上设置。 所以不需要添加BOM来设置编码。

像这样的东西应该为你工作。

 Dim str As New StringBuilder For Each dr As DataRow In Me.NorthwindDataSet.Customers For Each field As Object In dr.ItemArray str.Append(field.ToString & ",") Next str.Replace(",", vbNewLine, str.Length - 1, 1) Next Try My.Computer.FileSystem.WriteAllText("C:\temp\testcsv.csv", str.ToString, False) Catch ex As Exception MessageBox.Show("Write Error") End Try