将GridView导出到Excel
1public static void ExportGridView(GridView gridView, string filename)
2 {
3 string attachment = "attachment; filename=" + filename + ".xls";
4 HttpResponse Response = HttpContext.Current.Response;
5 Response.ClearContent();
6 Response.ContentEncoding = Encoding.GetEncoding("GB2312");
7 Response.AddHeader("content-disposition", attachment);
8 Response.ContentType = "application/ms-excel";
9 StringWriter sw = new StringWriter();
10 HtmlTextWriter htw = new HtmlTextWriter(sw);
11 // Create a form to contain the grid
12 HtmlForm frm = new HtmlForm();
13 gridView.Parent.Controls.Add(frm);
14 frm.Attributes["runat"] = "server";
15 frm.Controls.Add(gridView);
16 frm.RenderControl(htw);
17 //GridView1.RenderControl(htw);
18 Response.Write(sw.ToString());
19 Response.End();
20 }
2 {
3 string attachment = "attachment; filename=" + filename + ".xls";
4 HttpResponse Response = HttpContext.Current.Response;
5 Response.ClearContent();
6 Response.ContentEncoding = Encoding.GetEncoding("GB2312");
7 Response.AddHeader("content-disposition", attachment);
8 Response.ContentType = "application/ms-excel";
9 StringWriter sw = new StringWriter();
10 HtmlTextWriter htw = new HtmlTextWriter(sw);
11 // Create a form to contain the grid
12 HtmlForm frm = new HtmlForm();
13 gridView.Parent.Controls.Add(frm);
14 frm.Attributes["runat"] = "server";
15 frm.Controls.Add(gridView);
16 frm.RenderControl(htw);
17 //GridView1.RenderControl(htw);
18 Response.Write(sw.ToString());
19 Response.End();
20 }