在做项目时经常要用到将数据导出到Excel文件或是Word文件中,今天在http://www.wwwcoder.com/main/parentid/254/site/5334/68/default.aspx看到Exporting Data Grid to Excel这篇文章后,就把它小改一下,输出GridView的数据
如果单写这些代码会出现错误:
protected void Button1_Click(object sender, EventArgs e)
{
//导出GridView到Excel表的的按钮
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);//GridView1为GridView的ID
Response.Write(stringWrite.ToString());
Response.End();
}
protected void Button2_Click(object sender, EventArgs e)
{
//导出GridView到Word的的按钮
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Label1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
{
//导出GridView到Excel表的的按钮
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);//GridView1为GridView的ID
Response.Write(stringWrite.ToString());
Response.End();
}
protected void Button2_Click(object sender, EventArgs e)
{
//导出GridView到Word的的按钮
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
Label1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
如果单写这些代码会出现错误:
类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内
错误提示:
类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内
可能的解决方案:
在后台文件中重载VerifyRenderingInServerForm方法,如:
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}