GridView简单实现导出数据到Excel
按钮事件代码如下:
1 protected void LinkButton1_Click(object sender, EventArgs e)
2 {
3 Response.ClearContent();
4
5 Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
6
7 Response.ContentType = "application/excel";
8
9 StringWriter sw = new StringWriter();
10
11 HtmlTextWriter htw = new HtmlTextWriter(sw);
12 this.GridView1.RenderControl(htw);
13 Response.Write(sw.ToString());
14 Response.End();
15 }
16
2 {
3 Response.ClearContent();
4
5 Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
6
7 Response.ContentType = "application/excel";
8
9 StringWriter sw = new StringWriter();
10
11 HtmlTextWriter htw = new HtmlTextWriter(sw);
12 this.GridView1.RenderControl(htw);
13 Response.Write(sw.ToString());
14 Response.End();
15 }
16
注:必须重写一下方法,可以不实现.
1 public override void VerifyRenderingInServerForm(Control control){}
2
2