引言: 前幾天 在做web項目的時候 需要導出頁面上的數據 到Excel里面 但有的時候出現亂碼(有de時候不出現 很奇怪) 原來的代碼是這樣的: HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=FileName.xls"); HttpContext.Current.Response.Charset = "GB2312"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//.Unicode;//.UTF8;// HttpContext.Current.Response.ContentType = "xls"; //"application/vnd.xls"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); mygridview.RenderControl(htw); HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); 如何解決? 修改為下面的代碼 問題就解決了 HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.Write("
"); HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls"); HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); HttpContext.Current.Response.ContentType = "application/excel"; System.IO.StringWriter sw = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); mygridview.RenderControl(htw); HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); 仔細比較一下 就是 HttpContext.Current.Response.Write("
"); 這句話起的作用 (這句話的作用是聲明該網頁使用gb2312進行編碼) 原來是 HttpContext.Current.Response.Charset = "GB2312"; 我以為有這句話 就可以 看來不行 還是 使用
比較保險