ASP.NET Excel export encoding problem

前端 未结 6 1491
-上瘾入骨i
-上瘾入骨i 2020-11-27 03:44

I\'m doing some Excel Exports on the ASP.NET Site. Everything works except of the Encoding. When I open it in Excel, it looks like this:

Eingabe Koste

相关标签:
6条回答
  • 2020-11-27 04:09

    Have you tried setting the encoding in a meta tag in the HTML?

    <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
    

    Excel won't see the response headers, so it won't know what the Response.Encoding is. The meta tag allows it to find out.

    0 讨论(0)
  • 2020-11-27 04:12

    You can try to use "Server.HtmlDecode" to decode these words like "João"

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e){
    String wrong = "Jo&#227;o";
    String corrected = Server.HtmlDecode(wrong);}
    
    0 讨论(0)
  • 2020-11-27 04:16

    For instances where UTF8 is needed...

    FileInfo dataExportFile = new FileInfo(dsExport.Tables[0].Rows[0]["DataExportFile"].ToString());
    
    Response.Clear();
    Response.ContentType = "application/ms-excel";                        
    Response.AddHeader("Content-Disposition", "attachment;filename=" + dataExportFile.Name);
    Response.ContentEncoding = System.Text.Encoding.UTF8;
    Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
    Response.TransmitFile(dataExportFile.FullName);
    
    0 讨论(0)
  • 2020-11-27 04:18

    add Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

    0 讨论(0)
  • 2020-11-27 04:19

    Well I found out that the problem could be in the header of the excel file, that it does not contain the BOM byte sequence (at the beginning of the file representing the encoding used).

    So I made it this way and it works for me:

    Response.Clear();
    Response.AddHeader("content-disposition","attachment;filename=Test.xls");   
    Response.ContentType = "application/ms-excel";
    Response.ContentEncoding = System.Text.Encoding.Unicode;
    Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
    
    System.IO.StringWriter sw = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
    
    FormView1.RenderControl(hw);
    
    Response.Write(sw.ToString());
    Response.End(); 
    
    0 讨论(0)
  • 2020-11-27 04:19

    I got same problem with spanish characters and solved it with this line of code.

            response.ContentEncoding = System.Text.Encoding.Default ;
    

    hope this helps

    0 讨论(0)
提交回复
热议问题