asp.net 导出GridView、其它控件到Excel(防止中文乱码)

来源:互联网 发布:java返回页面 编辑:程序博客网 时间:2024/05/16 18:04
/// <summary>
        /// 导出到EXCEL
        /// </summary>
        /// <param name="ctl"></param>
        /// <param name="FileName"></param>
        public void ToExcel(System.Web.UI.Control ctl, string FileName)
        {
            HttpContext.Current.Response.Charset = "GB2312"; // 或UTF-7 以防乱码
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            //HttpContext.Current.Response.ContentType = "application/octet-stream";
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");//出现中文乱码加这句
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" +                   System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(FileName)) + ".xls");
            ctl.Page.EnableViewState = false;
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            ctl.RenderControl(hw);
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.End();
            ctl.Page.EnableViewState = false;
        }
0 0
原创粉丝点击