Search code examples
c#asp.netexcelepplus

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


Solution

  • 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_your_file.xls");
        Response.BinaryWrite(bytes);
        Response.End();
    }