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.
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.
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");
...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With