Vinit Patel

Export DataGrid/GridView to Excel

Posted on: October 1, 2009


/// <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;
}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Calendar

October 2009
M T W T F S S
« Sep   Dec »
 1234
567891011
12131415161718
19202122232425
262728293031  

Stats Of Blog

  • 6,824 hits

Cluster Map

%d bloggers like this: