Search code examples
excelsql-server-2008utf-8exportunicode-string

Exporting from GridView to Excel is not show Persian correctly


Bind the GridView by SqlDataSource and I wrote below code to export from GridView to Excel:

System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
gvReportPrint.GridLines = GridLines.Both;
gvReportPrint.Font.Name = "'BYekan'";

foreach (GridViewRow row in gvReportPrint.Rows)
{
    row.Cells[2].Attributes.Add("class", "textmode");
}

string style = @"<style> .textmode { mso-number-format:\@; } </style>";
gvReportPrint.HeaderStyle.Font.Bold = true;
Response.Write(style);
gvReportPrint.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.End();

During Export From GridView to Excel, unicode characters don't show correctly, they are shown like this: --> Click this link to show the problem <--


Solution

  • It seems that you are using asp:GridView,I had the same issue and using GridView class solved it like below :

    public void ToExcel(DataTable dt, string reportName)
        {
            if (dt.Rows.Count > 0)
            {
                string filename = string.Format("{0}.xls", reportName);
    
                GridView gv = new GridView();
    
                gv.DataSource = dt;
                gv.HeaderStyle.BackColor = System.Drawing.Color.FromArgb(0, 119, 179);
                gv.HeaderStyle.ForeColor = System.Drawing.Color.FromArgb(250, 250, 250);
                gv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromArgb(191, 191, 191);
                gv.Font.Name = "Tahoma";
                gv.Font.Size = 10;
                gv.DataBind();
    
                System.IO.StringWriter sw = new System.IO.StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Unicode;
                HttpContext.Current.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
    
                gv.RenderControl(hw);
                HttpContext.Current.Response.Output.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
    

    and dt should be your data source for gridview.

    Also please take a look at ASP.NET Excel export encoding problem