Grid Export to Excel, Need to remove all hyperlinks

 Admin   
1535 View    Dec 23 2019 4:03PM

Hi,

 

To Remove the Hyperlink column and show only the text on Exported Excel. Please try the subsequent implementation Export to Excel Button Click

 

protected void Button1_Click(object sender, EventArgs e)
    {
        //Export the GridView to Excel
        PrepareGridViewForExport(GridView1);
        ExportGridView();
    }

Methods

 

private void ExportGridView()
    {
        string attachment = "attachment; filename=Contacts.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        GridView1.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
    }
 
    private void PrepareGridViewForExport(Control gv)
    {
        Literal l = new Literal();
        string name = String.Empty;
        for (int i = 0; i < gv.Controls.Count; i++)
        {
            //Removing the Hyperlink from Hyperlink column and assigning the text to literal control
            if (gv.Controls[i].GetType() == typeof(HyperLink))
            {
                l.Text = (gv.Controls[i] as HyperLink).Text;
                gv.Controls.Remove(gv.Controls[i]);
                gv.Controls.AddAt(i, l);
            }
            if (gv.Controls[i].HasControls())
            {
                PrepareGridViewForExport(gv.Controls[i]);
            }
        }
    }