Friday, February 26, 2010

Export Gridview data to an Excel sheet

protected void imgExport_Click(object sender, ImageClickEventArgs e)
{
PrepareGridViewForExport(gvAttendance);
string attachment = "attachment; filename=CounsellingDetails.xls ";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
//GridView gv = new GridView();
//gv.DataSource = GetResults();
//gv.DataBind();
gvAttendance.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{

}
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]);

}

}

}

1 comment:

Followers