如何将用户控件中的asp网格视图导出为ex​​cel?

时间:2015-01-18 13:40:31

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

我在网页中的WebUserControl中有一个GridView,它使用母版页,我需要将网格数据导出为ex​​cel和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.

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

1 个答案:

答案 0 :(得分:0)

我找到了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