【问题标题】:Cannot export symbols to Excel from gridview无法从 gridview 将符号导出到 Excel
【发布时间】:2016-07-08 21:07:53
【问题描述】:

我正在将 gridview 导出到 excel,我正在成功导出。但是在我的 gridview 中,我有一些特殊符号,例如(•、“”、'、-、_)这些类型的符号无法导出,而不是我所在的地方变得像(–,“,â€,’)这个。 我怎么能克服这些问题。这是我将gridview导出到excel的代码?

Response.Clear();
Response.Buffer = true;          
Response.AddHeader("content-disposition", "attachment;filename=demo.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvDetails.AllowPaging = false;
gvDetails.DataSource = dt1;
gvDetails.DataBind();
for (int i = 0; i < gvDetails.Rows.Count; i++)
{
    GridViewRow row = gvDetails.Rows[i];            
    row.Attributes.Add("class", "textmode");
}
gvDetails.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();

【问题讨论】:

    标签: c# asp.net excel gridview


    【解决方案1】:

    您需要指定并提供编码信息。

    Response.ContentEncoding = System.Text.Encoding.Unicode; /*c# uses UTF-16 internally*/
    ...
    Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble()); /*Include the UTF-16 header so excel will treat this as UTF-16*/ Response.Output.Write(sw.ToString());
    ...

    请注意,这不是最好的解决方案,理想情况下您应该使用 OpenXML 或其他一些库来导出到 excel。

    【讨论】:

      【解决方案2】:

      请将您的内容类型更改为以下,

      Response.ContentType = "application/ms-excel";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多