如何将DataGrid导出到客户端的Excel中
注意:下面代码是用于使用了分页的DataGrid中,如果未使用自带的分页功能,则相应的地方要进行修改.具体的看下代码就懂了.
1 private void btnMIME_Click(object sender, System.EventArgs e)
2 {
3 Response.ContentType = "application/vnd.ms-excel";
4 Response.Charset = "";
5 this.EnableViewState = false;
6 System.IO.StringWriter sw = new System.IO.StringWriter();
7 System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
8 int nCur = dgShow.CurrentPageIndex;
9 int nSize = dgShow.PageSize;
10
11 dgShow.AllowPaging = false;
12 BindData();//重新绑定数据
13
14 dgShow.Columns[7].Visible =false;
15 dgShow.RenderControl(hw);
16 dgShow.Columns[7].Visible =true;
17
18 //以下恢复分页
19 dgShow.AllowPaging = true;
20 dgShow.CurrentPageIndex = nCur;
21 dgShow.PageSize = nSize;
22 BindData();//重新绑定数据
23 Response.Write(sw.ToString());
24 Response.End();
25 }
2 {
3 Response.ContentType = "application/vnd.ms-excel";
4 Response.Charset = "";
5 this.EnableViewState = false;
6 System.IO.StringWriter sw = new System.IO.StringWriter();
7 System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
8 int nCur = dgShow.CurrentPageIndex;
9 int nSize = dgShow.PageSize;
10
11 dgShow.AllowPaging = false;
12 BindData();//重新绑定数据
13
14 dgShow.Columns[7].Visible =false;
15 dgShow.RenderControl(hw);
16 dgShow.Columns[7].Visible =true;
17
18 //以下恢复分页
19 dgShow.AllowPaging = true;
20 dgShow.CurrentPageIndex = nCur;
21 dgShow.PageSize = nSize;
22 BindData();//重新绑定数据
23 Response.Write(sw.ToString());
24 Response.End();
25 }
浙公网安备 33010602011771号