将DataGrid或GridView中的数据生成Excel

下面是一个将DataGrid中的数据生成Excel文档的方法,其中System.Web.UI.Control ctl指DataGrid的ID,

FileName指要生成Excel文件的名称。

//生成Excel文件
       public void ToExcel(System.Web.UI.Control ctl, string FileName)
       {
           //设置网络输出流的HTTP字符集为UTF-8,Current为当前 HTTP 请求获取 HttpContext 对象
           HttpContext.Current.Response.Charset = "GB2312";
           HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
           //设置输出流HTTPMIME类型为excel
           HttpContext.Current.Response.ContentType = "application/ms-excel";
           //将HTTP头添加到输出流
           HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+""+ FileName+".xls");
           //不保存该控件的视图状态
           ctl.Page.EnableViewState = false;
           System.IO.StringWriter sw = new System.IO.StringWriter();
           //将文本写入到输出流
           System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
           //将服务器控件的内容输出到HtmlTextWriter对象中
           ctl.RenderControl(hw);
           //StringWriter.ToString返回包含迄今为止写入到当前 StringWriter 中的字符的字符串
           HttpContext.Current.Response.Write(sw.ToString());
           HttpContext.Current.Response.End();
       
       }

posted @ 2007-11-13 23:00  黑羽飘舞  阅读(613)  评论(0编辑  收藏  举报