Suppress ASP.NET server control while exporting to Excel from Gridview

We normally use server side controls like textbox, dropdownlist, link button etc in gridview. What will happen when you export gridview to excel? Your excel will have textbox, dropdownlist etc as a control along with the value. That looks ugly when you have to send the excel report to the user.

Here I am goiing to explain what you have to do when you export the data from gridview to Excel if you have server controls in the Gridview.
What we will do is convert the all server controls in the gridview to literal and then we export that to Excel.

In below sample code you can see I am assigning the value fom checkbox and Textbox to a literal control. Extend the same to add link button, dropdownlist or for other server side controls.

    private void ExportApplication()
    {
        string Excelfilename = "ExcelSample" + DateTime.Now;
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/vnd.ms-excel";
        Response.AppendHeader("Content-Disposition:", "attachment; filename=" + Excelfilename + ".xls");
        Response.Charset = "";
        this.EnableViewState = false;
        System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
        this.ClearControls(Gridview1);
        GridView.RenderControl(oHtmlTextWriter);
        Response.Write(oStringWriter.ToString());
        Response.End();
    }
    private void ClearControls(Control control)
    {
        for (int i = control.Controls.Count - 1; i >= 0; i--)
        {
            ClearControls(control.Controls[i]);
        }
        if (!(control is TableCell))
        {
            if (control.GetType().GetProperty("SelectedItem") != null)
            {
                LiteralControl literal = new LiteralControl();
                control.Parent.Controls.Add(literal);
                try
                {
                    literal.Text = (string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);

                }
                catch
                {
                }
                control.Parent.Controls.Remove(control);
            }
            else
                if (control.GetType().GetProperty("Text") != null)
                {
                    LiteralControl literal = new LiteralControl();
                    control.Parent.Controls.Add(literal);
                    literal.Text = (string)control.GetType().GetProperty("Text").GetValue(control, null);
                    control.Parent.Controls.Remove(control);
                }
        }
        return;
    }

2 Comments

Comments have been disabled for this content.