[HowTo] Write Excel file to web page (aspx)

Writing an Excel file to the response object in ASP.NET is quite easy…

This piece of code works with most of the files type…

string YourFilename = "test.xlsx";
string path = Server.MapPath(YourPath + YourFilename); 

Response.ClearContent();
Response.AddHeader("content-disposition", "attachement;filename=" + YourFilename);

// Ouvrir avec MSExcel
Response.ContentType = "application/ms-excel";

// MSWord
// Response.ContentType = "application/msword";
// Text
// Response.ContentType = "text/plain";
// Stream
// Response.ContentType="application/octet-stream"

Response.Flush();
Response.WriteFile(path);
Response.End();

By Using ExcelPackage, you are also able to create your own Excel files from any piece of data


Leave a Reply