Friday, February 29, 2008

Export gridview to excel at button click

when u want to export a gridview at button click and one thing to note that grid view is present in master-content page then go for below code ::
protected void imgbtnExport_Click(object sender, ImageClickEventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Users.xls");
Response.Charset = "";
Response.ContentType = "~/ReportOutputs/abc.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView();



objDs = user.getUser();
if (objDs != null && objDs.Rows.Count > 0)
{
dg.DataSource = objDs;
dg.DataBind();
}


dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}

We have to generate a new grid view at runtime and have to bind the data to the new grid with the data previously present in the grid.
But if the grid view is in form tag then no need to generate a new gridview, just give the id of grid to rendercontrol and it will work.....

No comments: