Can I download an Excel file made from a memory stream off an ASP.NET page?

23,290

Solution 1

You want to specify the content-type and content-dispisition headers like so - Response.ContentType = "application/vnd.ms-excel" works in IE and firefox but not in Safari, then stream your file. Once complete, call Response.End() to stop the application execution

Code Sample:

void StreamExcelFile(byte[] bytes)
{
    Response.Clear();
    Response.ContentType = "application/force-download";
    Response.AddHeader("content-disposition", "attachment; filename=name_you_file.xls");
    Response.BinaryWrite(bytes);
    Response.End();
}

Solution 2

ExcelPackage pck = new ExcelPackage();
.....
.....
.....

byte[] bfr = pck.GetAsByteArray();
Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AppendHeader("content-disposition", "attachment; filename=ExcelFileName.xlsx");

Response.OutputStream.Write(bfr, 0, bfr.Length);
Response.Flush();
Response.Close();

Solution 3

Yes, look into using an HTTP Handler to stream the file to the browser from memory.

http://msdn.microsoft.com/en-us/library/ms972953.aspx

Share:
23,290
AbdelHady
Author by

AbdelHady

Updated on July 09, 2022

Comments

  • AbdelHady
    AbdelHady almost 2 years

    I have an ASP.NET page where a user provides an ID, and then we pull some data from the DB and put it into an Excel spreadsheet. I would like to create the Excel file in memory and then allow the user to download the file. I could create a file on the server, and then delete it afterwards, but it seems unnecessary. Depending on error handling I could potentially orphan a file with that approach, etc.

    Is something like this possible? Or do I need to use a file stream?

    On a side note, I'm using EPPlus as an API (quick plug for it).