8

I am trying to export the data to .xls file using below code

       GridView2.DataSource = dt;
       GridView2.DataBind();

        DirectoryInfo dir = new DirectoryInfo(@"C:\New List Reports");
        dir.Create();
        StringBuilder Excelfile = new StringBuilder("ExcelReport(");

        Excelfile.Append(DateTime.Now.ToString("MMM dd,HH.mm"));
        Excelfile.Append(").xls");
        FileInfo file = new FileInfo(@"C:\New List Reports\" + Excelfile);//C:\List Data\


        StreamWriter streamWriter = file.CreateText();

        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
        GridView2.RenderControl(htmlTextWriter);

        streamWriter.Write(stringWriter.ToString());

        htmlTextWriter.Close();
        streamWriter.Close();
        stringWriter.Close();
        Session.Remove("Tempdata");
        byte[] Content = File.ReadAllBytes(@"C:\New List Reports\" + file.Name);
        Response.ContentType = "application/vnd.ms-excel";
        Response.ContentEncoding = System.Text.Encoding.Unicode;

        Response.SetCookie(new HttpCookie("token", Request.Form["token"]));
        Response.AddHeader("content-disposition", "attachment; filename=" + file.Name);
        Response.BufferOutput = true;
        Response.OutputStream.Write(Content, 0, Content.Length);
        Response.End();

after exporting the data, character  gets appended to the currency field as shown £3.25 which is incorrect. how to get rid of Â.

Amal Hashim
  • 28,306
  • 5
  • 31
  • 61
Salim Mandrekar
  • 396
  • 1
  • 3
  • 15
  • 3
    I did a quick search and just in case that you haven't read http://stackoverflow.com/questions/1679656/asp-net-excel-export-encoding-problem yet I wanted to link it here if it could give you some pointers! :-) – Tenttu Sep 29 '14 at 10:30

2 Answers2

0

I know that's not the best solution and that's just a patch... but it gets the job done! It's important that you put some comments in your code telling why you do that.
So, after GridView2.RenderControl(htmlTextWriter);, try

htmlTextWriter.Position = 0;
string correctedXLS = new StreamReader(htmlTextWriter).ReadToEnd();
correctedXLS = correctedXLS.Replace(“£”, “£”);
stringWriter.Write(correctedXLS);
correctedXLS.Close();
Simon
  • 21
  • 5
0

You may want to try changing the encoding for the Response.ContentEncoding to use UTF-8.

I have not tested it but you can find some information here, https://msdn.microsoft.com/en-us/library/zs0350fy(v=vs.71).aspx

Robert Lindgren
  • 24,520
  • 12
  • 53
  • 79
Devon
  • 21
  • 3