ASP .NET: Dynamically creating/generating excel file at server and making it available to download

If you want that when user click on a particular link, based on his preferences an excel file should be generated dynamically and should be downloaded automatically at client. Here is small example how you can do it.

Trick is create a html file and present it as excel file ;).

for this follow the steps:

1.  Add a web form say xlImage.aspx, in your project.

2. Delete every thing from xlImage.aspx page except first line.

3. Now in code behind page, i.e., in xlImage.aspx.cs add following line on,

Page_Load function

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();

Response.Buffer = true;
Response.AddHeader(“content-disposition”, “attachment;filename=file.xls”);

Response.ContentType = “application/vnd.ms-excel”;

String imagepath = “<img src=’http://localhost:2290/Excel%20Export/pic/1.jpeg&#8217; width=’70’ height=’80’ style:’position: absolute;left:200px;’/>”;

Response.Output.Write(“\n<body>\n<html>”);

Response.Output.Write(“<center><table width=’800′ align=’center’ style=’text-align:center’ border=’1px’>”);
Response.Output.Write(“<tr><td></td><td></td><td></td><td></td><td colspan=’2′ align=’center’><div>” + imagepath + “</div></td></tr>”);
Response.Output.Write(“</table></center>”);
Response.Output.Write(“\n</body>\n</html>”);

Response.Flush();
Response.End();

same thing could be done for word file also.

Advertisements