I tried to follow up Ram's suggestion and exported data in a GridView to a word documents by following code snippet:
1 protected void Button1_Click(object sender, EventArgs e)
2 {
3 Response.Clear();
4 Response.Buffer = true;
5 Response.AddHeader("content-disposition", "attachment;filename=export.docx");
6 Response.ContentEncoding = System.Text.Encoding.UTF8;
7 Response.ContentType = "application/vnd.word";
8 System.IO.StringWriter strWriter = new System.IO.StringWriter();
9 System.Web.UI.HtmlTextWriter htmlTxtWriter = new HtmlTextWriter(strWriter);
10 this.gvCategory.RenderControl(htmlTxtWriter);
11 Response.Output.Write(strWriter.ToString());
12 Response.Flush();
13 Response.End();
14
2 {
3 Response.Clear();
4 Response.Buffer = true;
5 Response.AddHeader("content-disposition", "attachment;filename=export.docx");
6 Response.ContentEncoding = System.Text.Encoding.UTF8;
7 Response.ContentType = "application/vnd.word";
8 System.IO.StringWriter strWriter = new System.IO.StringWriter();
9 System.Web.UI.HtmlTextWriter htmlTxtWriter = new HtmlTextWriter(strWriter);
10 this.gvCategory.RenderControl(htmlTxtWriter);
11 Response.Output.Write(strWriter.ToString());
12 Response.Flush();
13 Response.End();
14
After building the project and try to view it in browser, however, the browser just told me the following message when clicking the Export data button:
After a quick search, I found: http://rstew.blogspot.com/2007/10/gridview-must-be-placed-inside-form-tag.html, great post, override the VerifyRenderingInServerForm method, the process works happily!
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
转载于:https://www.cnblogs.com/RoahnLuo/archive/2009/11/27/1612262.html