我能否从ASP.NET页面下载内存stream中创build的Excel文件?
我有一个用户提供一个ID的ASP.NET页面,然后我们从数据库中提取一些数据,并将其放入Excel电子表格中。 我想在内存中创buildExcel文件,然后允许用户下载文件。 我可以在服务器上创build一个文件,然后删除它,但似乎没有必要。 根据error handling,我可能会用这种方法孤立一个文件,等等。
是这样的可能吗? 或者我需要使用文件stream?
在附注中,我使用EPPlus作为API(快速插件)。
你想指定content-type
和content-dispisition
这样 – Response.ContentType =“application / vnd.ms-excel”在IE和firefox中可以使用,但不能在Safari中使用 ,然后stream式处理文件。 一旦完成,调用Response.End()
来停止应用程序的执行
代码示例:
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(); }
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();
是的,请使用HTTP处理程序将文件从内存中stream式传输到浏览器。
你正在寻找的是一个通用的处理程序:
http://www.dotnetperls.com/ashx
简而言之,您需要做的是定义上下文types。 在你的情况下将是一个xls或xlsx。 设置响应,并引导用户到处理程序。
他们将被提示下载文件。