UTF8 encoding and Excel CSV
Working with WebForms I often use ASHX handlers for generating stuff. It can be anything from XML to CSV.
This is very lightweight and I like it, but today I ran into a problem where I wanted to generate a CSV for Microsoft Excel, but Excel could not recognize the UTF encoding and tried to parse it as ANSI.
Looks like crap because Excel can't tell that we're feeding it UTF8. This can be fixed by explicitly giving the file a BOM (byte order mark).
// Start the feed with BOM
context.Response.BinaryWrite(Encoding.UTF8.GetPreamble());
var data = new[]
{
"Namn;Land;Poäng", // Name;Country;Points
"Mikael Lundin;Sverige;1200",
"John Smith;US;800",
"Jean-Pierre Bordeaux;Française;600"
};
foreach (var rows in data)
context.Response.Write(rows + "\n");
}
The magic happens at line 8 where we explicitly write the BOM to the stream.
comments powered by Disqus