如何将用户控件内的 asp 网格视图导出到 excel?

How to export asp grid view inside a user control to excel?

我在使用母版页的网页中的 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 服务器。

好吧,我找到了 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. 中解决了
  3. 我还发现这个示例代码可以以许多其他格式导出 Export GridView to doc/access/csv/Excel/pdf/xml/html/text/print