/// <param name="FileType">文件类型:application/ms-excel</param>
/// <param name="FileName">文件名字</param>
/// <param name="gridview"></param>
public static void ExportToExcel(this Page _page, string FileType, string FileName, GridView gridview)
{
_page.Response.Clear();
_page.Response.Buffer = true;
_page.Response.Charset = "utf-8";
_page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
_page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8).ToString());
_page.Response.ContentType = FileType;
这行很重要,是解决乱码的关键之所在。
_page.Response.Write("<meta http-equiv=Content-Type content=/"text/html; charset=utf-8/">");
_page.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
gridview.RenderControl(hw);
_page.Response.Output.Write(tw.ToString());
_page.Response.Flush();
_page.Response.End();
}
最初尝试各种办法,换各种编码,偶尔还是有gridview会出现乱码。原因是各个gridview的stream不一样,编码或许会出现问题。
最终还是靠加粗的那行代码,解决了问题。