Thursday, February 17, 2011

Remove ’s while exporting excel file using RenderControl method of GridView or DataGrid or DataList control.

Example: ‘Employee’s home’ was coming like ‘Employee’s home’ while exporting to excel file where it should come like the original one.

Code Snippet:
Function  ExportToExcel( GridView  gv)
{
HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Test.xls"));
            HttpContext.Current.Response.ContentType = "application/ms-excel";


            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();

            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

           
            gv.RenderControl(oHtmlTextWriter);

 // add the below marked line to fix that issue
            HttpContext.Current.Response.ContentEncoding = Encoding.GetEncoding("Windows-1252");

            HttpContext.Current.Response.Write(strHeading + oStringWriter.ToString());

            HttpContext.Current.Response.End();

}