可以从ASP.NET页面下载从内存流中创建的Excel文件吗? [英] Can I download an Excel file made from a memory stream off an ASP.NET page?

查看:161
本文介绍了可以从ASP.NET页面下载从内存流中创建的Excel文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET页面,用户提供一个ID,然后我们从数据库中提取一些数据并将其放入Excel电子表格中。我想在内存中创建Excel文件,然后允许用户下载文件。我可以在服务器上创建一个文件,然后删除它,但似乎没有必要。根据错误处理,我可能会用这种方法孤立一个文件等。



有可能吗?还是需要使用文件流?



在旁注中,我使用 EPPlus 作为API(快速插件)。

解决方案

内容类型内容分配标题如下 - Response.ContentType =application / vnd.ms-excel在IE和Firefox中工作,但不在Safari中,然后流式传输您的文件。一旦完成,请调用 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();
}


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

解决方案

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

这篇关于可以从ASP.NET页面下载从内存流中创建的Excel文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆