Link to home
Start Free TrialLog in
Avatar of dynamicweb09
dynamicweb09Flag for India

asked on

Export to excel with c# custom Control



I want to create custom Button control in c#.On Click on the Button the data in gridview will be Exported To Excell.
i have tried.
Below are some code
protected override void OnClick(EventArgs e)
        {
            base.OnClick(e);

            foreach (Control c in this.Page.Controls)
            {
                String s = c.GetType().ToString();
                if (c is GridView)
                {
                    GridView gv = (GridView)c;
                    if (gv != null)
                    {

                        ExportToExcell(gv);
                    }
                }
            }          
        }

        public void ExportToExcell(GridView gv)
        {
            string attachment = "attachment; filename=Data.xls";
            Context.Response.ClearContent();
            Context.Response.AddHeader("content-disposition", attachment);
            Context.Response.ContentType = "application/ms-excel";

            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            HtmlForm frm = new HtmlForm();

            gv.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(gv);
            frm.RenderControl(htw);
            Context.Response.Write(sw.ToString());
            Context.Response.End();
        }
Avatar of abdkhlaif
abdkhlaif
Flag of Saudi Arabia image

one way to do this is first to convert your gridview to a DataTable using the attached code then use the ExportToExcel method at (just copy & paste):
http://forums.asp.net/p/975095/1237999.aspx#1237999 
to convert the DataTable to Excel

protected void Button2_Click(object sender, EventArgs e)
{
	DataTable dt = new DataTable();

	// copy columns from the gridview to dt:
	foreach (TableCell tc in GridView1.HeaderRow.Cells)
		dt.Columns.Add(tc.Text);

	// import rows from gridview to dt:
	foreach (GridViewRow gvr in GridView1.Rows)
	{
		DataRow nr = dt.NewRow();
		for (int c = 0; c < dt.Columns.Count; c++)
			nr[c] = gvr.Cells[c].Text;
		
		dt.Rows.Add(nr);
	}

	// convert dt to Excel file:
	ExportToExcel(dt);
}

Open in new window

Avatar of dynamicweb09

ASKER

how will i write all the code within custom control.
ASKER CERTIFIED SOLUTION
Avatar of abdkhlaif
abdkhlaif
Flag of Saudi Arabia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial