Friday, January 29, 2010

C#: Exporting the Table content of an HTML Page on Button Click to MS Excel.

Exporting the Table content of an HTML Page on Button Click to MS Excel.

protected void Button1_Click(object sender, EventArgs e)
{
string fileName = "CompanyProfile.xls";

HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

HtmlForm oFrm = new HtmlForm();

tblExport.Parent.Controls.Add(oFrm);
oFrm.Attributes["runat"] = "server";
oFrm.Controls.Add(tblExport);
oFrm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

}

Export a GridView Content to MS Excel : C# (Few more Find Controls to be added if the Gridview has some controls in it.)

private void ExportGridView()

{
string attachment = "attachment; filename=SalesVsExpenses.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
// Create a form to contain the grid
HtmlForm frm = new HtmlForm();
GrvMerged.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(GrvMerged);
frm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Method, if GridView has some controls in it.

private static void PrepareControlForExport(Control control)
{
int i = 0;
while ((i < control.Controls.Count))
{
Control current = control.Controls[i];
if ((current is LinkButton))
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl(((LinkButton)current).Text));
}
else if ((current is ImageButton))
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl(((ImageButton)current).AlternateText));
}
else if ((current is HyperLink))
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl(((HyperLink)current).Text));
}
else if ((current is DropDownList))
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl(((DropDownList)current).SelectedItem.Text));
}
else if ((current is CheckBox))
{
control.Controls.Remove(current);
control.Controls.AddAt(i, new LiteralControl(((CheckBox)current).Checked.ToString()));
}if (current.HasControls())
{PrepareControlForExport(current);}
i = (i + 1);
}
}