Tags: Blog |
Categories: Blog
Posted by
admin on
3/9/2009 5:56 PM |
Comments (4)
Got to my attention the code on this old post is all screw up, please find the right version below.
/// <summary>
/// Summary description for ExportToExcel.
/// </summary>
public class ExportToExcel
{
private Page m_pPage = null;
public ExportToExcel(Page pPage)
{
m_pPage = pPage;
}
public void ExportDataGrid(System.Web.UI.WebControls.DataGrid dg)
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
//export to excel
context.Response.Clear();
context.Response.Buffer= true;
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.Charset = "";
m_pPage.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(dg);
dg.RenderControl(oHtmlTextWriter);
context.Response.Write(oStringWriter.ToString());
context.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;
}
}
You can also download it from here
Enjoy
Al
d6644562-2924-402d-87cd-b2697b135ad9|0|.0