2

I Use This Code For Convert Grid View To Excel:

        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            Page.ResponseEncoding = "UTF-8";// System.Text.Encoding.UTF8;
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.HeaderEncoding = System.Text.Encoding.UTF8;
            //To Export all pages
            gvProduct.AllowPaging = false;

            gvProduct.HeaderRow.BackColor = Color.White;
            foreach (TableCell cell in gvProduct.HeaderRow.Cells)
            {
                cell.BackColor = gvProduct.HeaderStyle.BackColor;
            }
            foreach (GridViewRow row in gvProduct.Rows)
            {
                row.BackColor = Color.White;
                foreach (TableCell cell in row.Cells)
                {
                    if (row.RowIndex % 2 == 0)
                    {
                        cell.BackColor = gvProduct.AlternatingRowStyle.BackColor;
                    }
                    else
                    {
                        cell.BackColor = gvProduct.RowStyle.BackColor;
                    }
                    cell.CssClass = "textmode";

                }
            }

            gvProduct.RenderControl(hw);

            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            var a = Response.Output.Encoding;
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();

But When My Grid View Contain Persian Character After Export Those Have not Correct. I Think When Export, I Should Set Encoding. Please Help Me. Thanks.

1 Answer 1

3

try this

    Response.Clear();
    Response.Buffer = true;
    Response.AddHeader("content-disposition",
    "attachment;filename=Export.xls");
    Response.Charset = "";
    Response.ContentType = "application/vnd.ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    GridView1.AllowPaging = false;
    GridView1.DataBind();

    GridView1.RenderControl(hw);
    //style to format numbers to string
    string style = @"<style> .textmode { mso-number-format:\@; } </style> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>";
    Response.Write(style);
    Response.Output.Write(sw.ToString());
    Response.Flush();
    Response.End();`

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.