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

让人想犯罪 __ 提交于 2019-12-07 13:53:10

问题


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


回答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();
}



回答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();



回答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




回答4:


What you're looking for is called a generic handler:

http://www.dotnetperls.com/ashx

In a nutshell, what you need to do is define the context type. Which in your case will be a xls or xlsx. Set the response, and direct the user to the handler.

They will be prompted to download the file.



来源:https://stackoverflow.com/questions/9777185/can-i-download-an-excel-file-made-from-a-memory-stream-off-an-asp-net-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!