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
You want to specify headers content-type
and content-dispisition
for example: Response.ContentType = "application / vnd.ms-excel" 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.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=name_you_file.xls");
Response.BinaryWrite(bytes);
Response.End();
}
source to share
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();
source to share
What you are looking for is called a generic handler:
http://www.dotnetperls.com/ashx
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.
source to share