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

标签 c# excel utf-8 httpcontent

我在使用 Web API Controller 的 get 方法时遇到问题。此方法返回一个 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;

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

非常感谢。

最佳答案

如上所述,这在 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;
}

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

使用 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");
    ...
}

添加 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;
}

选择您最喜欢的解决方案。

关于C# 无法将欧元符号打印到文件中(使用 Excel 打开时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18352448/

相关文章:

excel - 如何处理条件格式公式中的双引号

excel - Officejs 添加/激活新工作表抛出 GeneralException

c# - 无法使用 DotNetZip 1.9 从 HttpInputStream 读取 zip 文件

vba - 如何以编程方式更改 VBA 项目的条件编译属性

c# - 如果仅删除一条边,Dijkstra 最短路径快速重新计算

c++ - Mysql截断难读字符

ruby-on-rails - ASCII-8BIT 中的 Rails 编码

java - javascript默认支持UTF-8吗

c# - 输出表达式值类似常数

c# - dotnet build 在 mac m1 上失败,出现零错误和警告