Displaying CSV in an Excel Worksheet from ASP.NET

Several times in the past I have needed to provide CSV data to users for use in MS Excel. Previously I have written code to create the physical file on the server and then redirect the user’s browser to that file for download/opening. However this approach has two major drawbacks.

  1. You must have rights to create files on the server.
  2. You can easily end up with loads of temporary files on the server which need clearing.

This morning I discovered a new way to achieve this without creating any physical csv files on the server by changing the content type and page header. The following code demonstrates this:

 

@{
    Response.ContentType = "application/vnd.excel";
    Response.AddHeader("Content-Disposition", "attachment; filename=filename.csv");

    Response.Write("aaa,bbb,ccc,ddd,eee,fff,ggg");
    Response.Write("hhh,iii,jjj,kkk,lll,mmm,nnn");
    Response.Write("ooo,ppp,qqq,rrr,sss,ttt,uuu");
} 


This way no physical file is ever created and the document will be displayed in an Excel worksheet. It is important to note though that the user must have Excel installed for this to work or they will receive an operating system message asking them to choose a program to use to open the file.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)