Monday, 15 August 2011

Export into Excel from gridview

In this article you will learn how to export data from gridview into excel in asp.net c#.

on of my friend told me that he facing problem to export data from gridview into excel when he is using updatepanel, then i feel to write this code.

// write this code in our export button click event 

protected void export_click(object sender, EventArgs e){

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=export.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
this.ClearControls(GridViewName);
GridViewName.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

}


//Also add this function to clear the controls 
private void ClearControls(Control ctrl)
{
for (int i = ctrl.Controls.Count - 1; i >= 0; i--)
{
ClearControls(ctrl.Controls[i]);
}

if (!(ctrl is TableCell))
{
if (ctrl.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
ctrl.Parent.Controls.Add(literal);
try
{
literal.Text = (string)ctrl.GetType().GetProperty("SelectedItem").GetValue(ctrl, null);
}

catch
{
}
ctrl.Parent.Controls.Remove(ctrl);
}

else if (ctrl.GetType().GetProperty("Text") != null)
{
if (ctrl.Visible == true)
{
LiteralControl literal = new LiteralControl();
ctrl.Parent.Controls.Add(literal);
literal.Text = (string)ctrl.GetType().GetProperty("Text").GetValue(ctrl, null);
ctrl.Parent.Controls.Remove(ctrl);

}
}
}
return;

}

public override void VerifyRenderingInServerForm(Control control)
{

}

No comments:

Post a Comment