DataGrid 导出 Excel 中文乱码

public static void DataGridToExcel(DataGrid dataGrid, string fileName)
{
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            // 1. Set ContentEncoding
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
            // 2. Set harset
            HttpContext.Current.Response.Charset = "utf-8";
            HttpContext.Current.Response.AppendHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            
            var sw = new StringWriter();
            var htmlw = new HtmlTextWriter(sw);

            dataGrid.RenderControl(htmlw);
            // 3. Set meta data
            HttpContext.Current.Response.Write("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=utf-8\"/>");
            HttpContext.Current.Response.Write(sw.ToString());
            HttpContext.Current.Response.End();
}

posted @ 2014-06-05 10:05  踏歌长行  阅读(426)  评论(0编辑  收藏  举报