简体   繁体   English

CSV编码问题(Microsoft Excel)

[英]CSV encoding issues (Microsoft Excel)

I am dynamically creating CSV files using C#, and I am encountering some strange encoding issues. 我使用C#动态创建CSV文件,我遇到了一些奇怪的编码问题。 I currently use the ASCII encoding, which works fine in Excel 2010, which I use at home and on my work machine. 我目前使用ASCII编码,它在Excel 2010中运行良好,我在家里和工作机器上使用它。 However, the customer uses Excel 2007, and for them there are some strange formatting issues, namely that the '£' sign (UK pound sign) is preceded with an accented 'A' character. 但是,客户使用Excel 2007,对他们来说有一些奇怪的格式问题,即'£'符号(英镑符号)前面带有重音'A'字符。

What encoding should I use? 我应该使用什么编码? The annoying thing is that I can hardly test these fixes as I don't have access to Excel 2007! 令人烦恼的是,我无法测试这些修复,因为我无法访问Excel 2007!

I'm using Windows ANSI codepage 1252 without any problems on Excel 2003. I explicitly changed to this because of the same issue you are seeing. 我在Excel 2003上使用Windows ANSI代码页1252没有任何问题。由于您遇到的相同问题,我明确地改为此。

private const int WIN_1252_CP = 1252; // Windows ANSI codepage 1252

this._writer = new StreamWriter(fileName, false, Encoding.GetEncoding(WIN_1252_CP));

I've successfully used UTF8 encoding when writing CSV files intended to work with Excel. 我在编写用于Excel的CSV文件时成功使用了UTF8编码。

The only problem I had was making sure to use the overload of the StreamWriter constructor that takes an encoding as a parameter. 我遇到的唯一问题是确保使用StreamWriter构造函数的重载,该构造函数将编码作为参数。 The default encoding of StreamWriter says it is UTF8 but it's really UTF8-Without-A-Byte-Order-Mark and without a BOM Excel will mess up characters using multiple bytes. StreamWriter的默认编码表示它是UTF8,但它确实是UTF8-Without-A-Byte-Order-Mark而没有BOM Excel将使用多个字节搞乱字符。

You need to add Preamble to file: 您需要将Preamble添加到文件:

        var data = Encoding.UTF8.GetBytes(csv);
        var result = Encoding.UTF8.GetPreamble().Concat(data).ToArray();
        return File(new MemoryStream(result), "application/octet-stream", "file.csv");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM