从GridView导出到Excel不正确地显示波斯语

绑定GridView的SqlDataSource,我写下面的代码从GridView导出到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(); 

在从GridView导出到Excel的过程中,unicode字符不能正确显示,它们显示如下: – >单击此链接显示问题< –

看来你正在使用asp:GridView ,我有同样的问题,并使用GridView class解决它,如下所示:

 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(); } } 

dt应该是你gridview的数据源。

也请看看ASP.NET的Excel导出编码问题