C# ASP.NET GridView导出EXCEL。

来源:互联网 发布:产品进入淘宝首页 编辑:程序博客网 时间:2024/05/21 11:25

C# CODE:

using System.IO;

using System.Web.UI;

        public void GridViewToExcel(Control ctrl)
        {
            try
            {
                HttpContext.Current.Response.Charset = "GB2312";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;//注意编码
                HttpContext.Current.Response.AppendHeader("Content-Disposition",
                    "attachment;filename=" + HttpUtility.UrlEncode("CurrentTaskStates.xls", System.Text.Encoding.UTF8).ToString());
                HttpContext.Current.Response.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 
                ctrl.Page.EnableViewState = false;
                StringWriter tw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(tw);
                ctrl.RenderControl(hw);
                HttpContext.Current.Response.Write(tw.ToString());
                HttpContext.Current.Response.End();
            }
            catch
            {
                //log.WriteLog(ex);
                // return;
            }
        }

 public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);


        }///重载,这个一定要有。

0 0