Is it possible to load an Excel file from a memory stream from an ASP.NET page?

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

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

On the side of the note, I am using EPPlus as the API (a quick plugin for it).


source to share

4 answers

You want to specify headers content-type

and content-dispisition

for example: Response.ContentType = "application /" works in IE and firefox but not Safari and then uploads your file. After the call ends Response.End()

, to stop the execution of the application

Sample code:

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




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




Yes, look at using an HTTP handler to stream a file to the browser from memory.



What you are looking for is called a generic handler:

In short, you need to define the type of context. Which in your case would be xls or xlsx. Set the answer and direct the user to the handler.

They will be prompted to download the file.



All Articles