簡體   English   中英

C#無法將歐元符號打印到文件中(使用Excel打開時)

[英]C# Unable to print euro symbol into a file (when opening with Excel)

我有一個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;

當我打開文件時,歐元符號無法正確顯示。 你能給我一個答案嗎?

非常感謝。

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

采取您最喜歡的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM