C#无法将欧元符号打印到文件中(使用Excel打开时)
我对web api控制器中的get方法有问题。此方法返回一个HttpResponseMessage对象,该对象包含一个带有csv文件的HttpContent,该文件包含欧元符号。当该方法返回文件时,不会打印欧元符号。 该方法的代码如下所示:C#无法将欧元符号打印到文件中(使用Excel打开时),c#,excel,utf-8,httpcontent,C#,Excel,Utf 8,Httpcontent,我对web api控制器中的get方法有问题。此方法返回一个HttpResponseMessage对象,该对象包含一个带有csv文件的HttpContent,该文件包含欧元符号。当该方法返回文件时,不会打印欧元符号。 该方法的代码如下所示: string export = ... //string with fields separed by ';' and with euro symbol HttpResponseMessage response = new HttpResponseMessa
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中不起作用,因为欧元符号没有正确显示(尽管在任何纯文本编辑器中都有) 我发现以下解决方案似乎工作正常 使用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;
}
选择您最喜欢的解决方案。什么是“显示不正确”?它在那里吗?可能您正在以错误的编码打开文件?请通过设置
response.ContentEncoding=System.Text.encoding.Utf8尝试使用;response.Charset=encoding.BodyName代码>我看到的是–而不是€。我使用Excel.response.Content.Headers打开文件。ContentEncoding是只读属性。请注意,如果我使用记事本打开文件,将正确显示欧元符号。问题是,我想用Excel打开文件,有没有办法设置Excel单元格编码?谢谢使用Windows-1252编码刚刚为我省去了一点麻烦,答案应该得到更多的支持。这是我在对内容标题和编码进行了一天的研究后发现的唯一正确的解释。非常感谢。Windows-1252为我解决了这个问题。谢谢
[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;
}