【问题标题】:Create file export and save from ASP.NET page从 ASP.NET 页面创建文件导出和保存
【发布时间】:2011-09-20 04:33:05
【问题描述】:

我有一个包含用户数据网格视图的 ASP.NET 网页。我需要在 gridview 中获取数据,生成一个 excel 文件,并允许用户将该 excel 文件保存到他们的本地机器上。

在代码中完成此任务的最佳方法是什么?是否可以显示文件保存对话框,然后在用户选择目录和文件名后从网格数据创建文件?我在软件开发中实现了这一点,但在 Web 开发中从未处理过。

谢谢

【问题讨论】:

  • 是的,您可以实现此使用文件流以字节形式获取文件数据,然后将这些字节分配给响应。检查此链接它将指导您如何打开文件对话框并允许用户在用户端保存文件。corymathews.com/397/…

标签: c# asp.net


【解决方案1】:

大多数人倾向于这样实现:

protected void btnExportToExcel_Click(object sender, EventArgs e)    
{
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");

        Response.Charset = "";         
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();        
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);        
        Response.Write(stringWrite.ToString());
        Response.End();
}

Source.

另一种选择(我更喜欢的那个)是使用EPPLus

【讨论】:

  • 和我说的完全一样。我也有那个代码但找不到它:)
  • 谢谢。像魅力一样工作!我在现有代码中稍微偏离了一点。网络开发 bleh。 :)
  • 如果您需要对生成的 Excel 进行更多控制,则为 EPPlus +1。它易于学习和使用,正是软件应有的方式。
猜你喜欢
  • 2017-11-01
  • 2015-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-30
  • 1970-01-01
  • 2015-09-05
  • 1970-01-01
相关资源
最近更新 更多