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 Â.

1

2 Answers 2

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();
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.