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.
- You must have rights to create files on the server.
- 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.













Steve,
It is amazing code. It worked for me once . Now it is still opening the excel , but no data in it. I checked the csv file and has data in it. What is wrong? please advice. Thanks