Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 851
Andrew Dunaway Avatar asked Dec 10 '22 01:12

Andrew Dunaway


1 Answers

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();
}
like image 94
dana Avatar answered Dec 11 '22 13:12

dana