【问题标题】:Exporting from GridView to Excel is not show Persian correctly从 GridView 导出到 Excel 无法正确显示波斯语
【发布时间】:2023-03-07 10:29:01
【问题描述】:

通过 SqlDataSource 绑定 GridView,我写了下面的代码从 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 字符无法正确显示, 它们显示如下: --> Click this link to show the problem <--

【问题讨论】:

    标签: excel sql-server-2008 utf-8 export unicode-string


    【解决方案1】:

    看来您使用的是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 export encoding problem

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多