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

3.3k views Asked by At

I have a problem with a get method into a web api controller. This method returns a HttpResponseMessage object which has a HttpContent with a csv file, which contains euro symbols. When the method returns the file, the euro symbol isn't printed. The code of the method is the following:

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;

When I open the file, the euro symbol doesn't appear correctly. Could you give me an answer?

Thanks a lot.

1

There are 1 answers

3
Juri On

As mentioned, this doesn't work in Excel as the € sign isn't shown properly (although it is in any plain text editor).

[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;
}

I found the following solutions that seem to work properly.

Use Windows-1252 encoding

It seems that by using Windows-1252 encoding Excel is able to correctly interpret the € symbol.

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

Prepend the BOM (Byte order mark)

Another solution that works is to append the correct BOM like this:

[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;
}

Take the solution you like most.