【问题标题】:How to export asp grid view inside a user control to excel?如何将用户控件内的asp网格视图导出到excel?
【发布时间】:2015-01-18 13:40:30
【问题描述】:

我在使用母版页的网页中的 WebUserControl 中有一个 GridView,我需要将网格数据导出为 excel 和 pdf。 我找到了这段代码:

Response.AppendHeader("content-disposition", "attachment;filename=ExportedHtml.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
((GridView)Hosts.FindControl("hostsGrid")).RenderControl(hw);
Response.Write(tw.ToString());
Response.End();

但是我收到了这个错误:

Control 'CPH_Body_Hosts_hostsGrid' of type 'GridView' must be placed inside 
a form tag with runat=server.

即使我在母版页上有一个表单 runat 服务器。

【问题讨论】:

  • 关于这个话题的文章相当多。该错误准确地说明了您必须在用户控件 aspx 文件中执行的操作,您必须用一个表单将 gridview 括起来,这通常不是您想要的。这还取决于您希望它在 Excel 中的外观。我们已经处理这个问题几个月了,最后决定编写我们自己的导出,它只需要网格数据源。缺点是很难使用网格的过滤器和分页并将其反映在导出中。

标签: c# asp.net gridview export-to-excel


【解决方案1】:

这个问题我找到了 2 个解决方案:

  1. 正如 King.code 所评论的,它已经在GridView must be placed inside a form tag with runat=“server” even after the GridView is within a form tag 中解决了
  2. 我还发现了这个以许多其他格式导出的示例代码Export GridView to doc/access/csv/Excel/pdf/xml/html/text/print

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    相关资源
    最近更新 更多