无法正确显示从GridView导出到Excel
通过SqlDataSource绑定GridView,我编写了以下代码将GridView导出到Excel:无法正确显示从GridView导出到Excel,excel,sql-server-2008,utf-8,export,unicode-string,Excel,Sql Server 2008,Utf 8,Export,Unicode String,通过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/v
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();
System.IO.StringWriter sw=new System.IO.StringWriter();
HtmlTextWriter hw=新的HtmlTextWriter(sw);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType=“application/vnd.ms excel”;
Response.AddHeader(“内容处置”、“附件;文件名=“+filename”);
gvReportPrint.GridLines=网格线。两者都是;
gvReportPrint.Font.Name=“'BYekan'”;
foreach(gvReportPrint.Rows中的GridViewRow行)
{
行。单元格[2]。属性。添加(“类”,“文本模式”);
}
字符串样式=@“.textmode{mso数字格式:\@;}”;
gvReportPrint.HeaderStyle.Font.Bold=true;
回应。写作(风格);
gvReportPrint.渲染控制(hw);
Response.Output.Write(sw.ToString());
Response.End();
从GridView导出到Excel时,unicode字符无法正确显示,
它们如下所示:
-->单击此链接显示问题您似乎正在使用
asp:GridView
,我遇到了相同的问题,并使用GridView类解决了问题,如下所示:
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的数据源
也请看一看