Analytics

2013年8月2日 星期五

[ASP.NET]解決 Gridview匯出excel時內容變成亂碼 (Export Gridview resolve when garbled excel content)


問題
Gridview匯出excel時內容變成亂碼



解決方法
public void ExportExcelFromGridView(GridView gv)
{
    string filename = "Excel1.xls";      
    HttpContext.Current.Response.ClearContent();
    //fix 亂碼加入下行
    HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
    System.IO.StringWriter sw = new System.IO.StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    gd.RenderControl(htw);
    HttpContext.Current.Response.Write(sw.ToString());
    HttpContext.Current.Response.End();
}

沒有留言:

熱門文章