Mojibake characters showing after exporting excel

843 Views Asked by At

I am not sure if anyone has encountered this problem. Here are the steps made to replicate the issue.

Steps: 1. Go to the List --> Contact Persons page. 2. Click on the "Export" button to generate .XLS report for the Contact Persons List. 3. Close the .XLS report and navigate to other pages e.g. Contacts List. 4. In the Contacts List, click on "Close" button to REDIRECT back to the "Contact Persons" list page.

Expected: - Page shoud display the Contact Persons List page.

Actual: - A strange page is displayed containing mojibaki characters. Please see image in this url https://i.stack.imgur.com/qao4C.png

here are the codes to generate the excel using an Active report:

private static void PushContentToHttp(ActiveReport report, MemoryStream msData, string fileName, string url) {

        report.Run();
        XlsExport xls = new XlsExport();
        xls.DisplayGridLines = true;
        xls.AutoRowHeight = true;
        xls.Export(report.Document, msData);

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Buffer = true;

        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.AddHeader("Content-Length", msData.Length.ToString());
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename= \"" + fileName + ".xls\"");
        HttpContext.Current.Response.AddHeader("Refresh", "3; url=" + url);
        HttpContext.Current.Response.Charset = "utf-8";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding(1252);
        //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
        HttpContext.Current.Response.BinaryWrite(msData.ToArray());
        HttpContext.Current.Response.End();
 //       HttpContext.Current.Response.Redirect(url,true);

    }

Any help would be very much appreciated! Thank you so much! :)

2

There are 2 best solutions below

0
On

actually, what's causing this, is your page tries to redirect back to the Excel page cached by the browser. what I could suggest is you do a complete redirect instead of doing just a browser back, so that the previous page, will completely load, instead of loading the cached Excel page. nothing to do with ANSI encode blah, blah, just a matter of incorrect redirection.

0
On

I'm betting this is because of Excel's default encoding is ANSI 125x, and you're trying to write it into UTF-8.

See this related SO question: Character encoding in Excel spreadsheet (and what Java charset to use to decode it)