解决GridView导出Excel后,分页,排序,中文乱码的问题

    /// <summary>
    /// 將Gridivew中的數據導出為Excel
    /// </summary>
    /// <param name="ctrl">Gridview名稱</param>
    /// <param name="FileName">要保存的文件名</param>
    public  void ExportToExcel(Control ctrl, String FileName)
    {
        GridView gv = (GridView)ctrl;
        gv.AllowPaging = false;//禁用Gridview的分页
      gv.AllowSorting = false;//禁用Gridview排序
      gv.DataBind();
        HttpContext.Current.Response.Charset = "GB2312";
        HttpContext.Current.Response.Charset = "";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");    
        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" +FileName); 
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=GB2312\">");
        gv.Page.EnableViewState = false;
        StringWriter tw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        gv.RenderControl(hw);
        HttpContext.Current.Response.Write(tw.ToString());
        HttpContext.Current.Response.End();
        
    }

 

因为很多页面需要导出Excel,所以我写了一个公共的方法,只需要传入GridView的id和预保存的Excel的fileName就OK了。

上面的方法解决了导出Excel后,分页,排序,中文乱码的问题,不会在Excel文件中出现分页和排序的链接,中英文都不会出在乱码。

posted @ 2010-07-28 11:21  斌斌NO1  阅读(1674)  评论(0编辑  收藏  举报