Monday, February 14, 2011

To Export the data from Gridview to Excel


protected void Button1_Click(object sender, EventArgs e)
{
string attachment = "attachment; filename=Employee.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        GridView1.RenderControl(htextw);
        Response.Write(stw.ToString());
        Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
    {

    }
If the GridView contains any controls, such as Checkboxes, Dropdownlists, we need to replace the contents with their relevant values. The following recursive function uses Reflection to determine the type of control. The control is deleted in preparation for the Excel export and the relevant value of the control is added.

private void PrepareGridViewForExport(Control gv)
{

    LinkButton lb = new LinkButton();
    Literal l = new Literal();
    string name = String.Empty;
    for (int i = 0; i < gv.Controls.Count; i++)
    {
        if (gv.Controls[i].GetType() == typeof(LinkButton))
        {
            l.Text = (gv.Controls[i] as LinkButton).Text;
  gv.Controls.Remove(gv.Controls[i]);
  gv.Controls.AddAt(i, l);
        }
        else if (gv.Controls[i].GetType() == typeof(DropDownList))
        {
            l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
            gv.Controls.Remove(gv.Controls[i]);
            gv.Controls.AddAt(i, l);
        }
        else if (gv.Controls[i].GetType() == typeof(CheckBox))
        {
            l.Text = (gv.Controls[i] as CheckBox).Checked? "True" : "False";
            gv.Controls.Remove(gv.Controls[i]);
            gv.Controls.AddAt(i, l);
        }
        if (gv.Controls[i].HasControls())
        {
            PrepareGridViewForExport(gv.Controls[i]);
        }
}

without  VerifyRenderingInServerForm method it will give an error
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server


or 

 protected void Button1_Click1(object sender, EventArgs e)
        {
            HtmlForm form = new HtmlForm();

            string attachment = "attachment; filename=Employee.xls";

            Response.ClearContent();

            Response.AddHeader("content-disposition", attachment);

            Response.ContentType = "application/ms-excel";

            StringWriter stw = new StringWriter();

            HtmlTextWriter htextw = new HtmlTextWriter(stw);

            form.Controls.Add(GridView1);

            this.Controls.Add(form);

            form.RenderControl(htextw);

            Response.Write(stw.ToString());

            Response.End();
        }

No comments:

Post a Comment