C#无法将欧元符号打印到文件中(使用Excel打开时)

use*_*468 4 c# excel utf-8 httpcontent

我有一个get方法进入web api控制器的问题.此方法返回一个HttpResponseMessage对象,该对象具有带有csv文件的HttpContent,该文件包含欧元符号.当方法返回文件时,不会打印欧元符号.该方法的代码如下:

string export = ... //string with fields separed by ';' and with euro symbol
HttpResponseMessage response = new HttpResponseMessage();
UTF8Encoding encoding = new UTF8Encoding();
Byte[] buffer = encoding.GetBytes(export);
response.Content = new ByteArrayContent(buffer);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "Export.csv" };
response.Content.Headers.ContentLength = export.Length;
response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddDays(1));
return response;
Run Code Online (Sandbox Code Playgroud)

当我打开文件时,欧元符号无法正确显示.你能给我一个答案吗?

非常感谢.

Jur*_*uri 8

如上所述,这在Excel中不起作用,因为€符号没有正确显示(尽管它在任何纯文本编辑器中).

[HttpPost("csv")]
public HttpResponseMessage GetCvsReport()
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    var content = "12€;3;test";
    var encoding = Encoding.UTF8;

    response.Content = new StringContent(content, encoding , "text/csv");
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = yourfile.csv"
    };

    return response;
}
Run Code Online (Sandbox Code Playgroud)

我发现以下解决方案似乎正常工作.

使用Windows-1252编码

似乎通过使用Windows-1252编码Excel能够正确解释€符号.

[HttpPost("csv")]
public HttpResponseMessage GetCvsReport()
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);

    var content = "12€;3;test";
    var encoding = Encoding.GetEncoding("Windows-1252");

    response.Content = new StringContent(content, encoding , "text/csv");
    ...
}
Run Code Online (Sandbox Code Playgroud)

前置BOM(字节顺序标记)

另一个有效的解决方案是附加正确的BOM,如下所示:

[HttpPost("csv")]
public HttpResponseMessage GetCvsReport()
{
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    var content = "12€;3;test";
    var encoding = Encoding.UTF8;
    content = encoding.GetString(new byte[] { 0xEF, 0xBB, 0xBF }) + content;    

    response.Content = new StringContent(content, encoding , "text/csv");
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = yourfile.csv"
    };

    return response;
}
Run Code Online (Sandbox Code Playgroud)

采取您最喜欢的解决方案.

  • 这个答案应该有更多的支持。这是我经过一天有关内容标头和编码的研究后找到的唯一正确的解释。谢谢! (2认同)