Skip to main content

UTF8 encoding and Excel CSV

Working with WebForms I often use ASHX handlers for generating stuff. It can be anything from XML to CSV.

Generic Handler

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.

Generic Handler

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).

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentEncoding = Encoding.UTF8;
    context.Response.ContentType = "text/csv";
    context.Response.AppendHeader("Content-Disposition", "attachment;filename=data.csv");

// 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