Public class ConvertExcel
{
Public void GridToExcel (System. Web. UI. Control ctl, bool clearControls)
{
HttpContext. Current. Response. AppendHeader ("Content-Disposition", "attachment?filename=excel.xls ");
HttpContext. Current. Response. Charset = "UTF-8 ";
HttpContext. Current. Response. Buffer = true;
HttpContext. Current. Response. ContentEncoding = System. Text. Encoding. Default;
HttpContext. Current. Response. ContentType = "application/ms-excel ";
Ctl. Page. EnableViewState = false;
System. IO. StringWriter tw = new System. IO. StringWriter ();
System. Web. UI. HtmlTextWriter hw = new System. Web. UI. HtmlTextWriter (tw );
If (clearControls = true)
{
ClearControls (ctl );
}
Ctl. RenderControl (hw );
HttpContext. Current. Response. Write (tw. ToString ());
HttpContext. Current. Response. End ();
}
Private void ClearControls (Control control)
{
For (int I = control. Controls. Count-1; I> = 0; I --)
{
ClearControls (control. Controls [I]);
}
If (! (Control is TableCell ))
{
If (control. GetType (). GetProperty ("SelectedItem ")! = Null)
{
LiteralControl literal = new LiteralControl ();
Control. Parent. Controls. Add (literal );
Try
{
Literal. Text = (string) control. GetType (). GetProperty ("SelectedItem"). GetValue (control, null );
}
Catch
{
}
Control. Parent. Controls. Remove (control );
}
Else
If (control. GetType (). GetProperty ("Text ")! = Null)
{
LiteralControl literal = new LiteralControl ();
Control. Parent. Controls. Add (literal );
Literal. Text = (string) control. GetType (). GetProperty ("Text"). GetValue (control, null );
Control. Parent. Controls. Remove (control );
}
}
Return;
}
}
ClearControl implementation: Convert the template in the Datagrid to Literal