Posts Tagged ‘ export data ’

Code For Export Data From DataGrid to Excel Sheet with C#


public static void ExportDataGridToExcel(DataGrid dgrdExport,Page pg)
		{
			try
			{
				pg.Response.Clear();
				pg.Response.Buffer= true;
				pg.Response.ContentType = "application/vnd.ms-excel";
				pg.Response.Charset = "";
				pg.EnableViewState = false;
				System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
				System.Web.UI.HtmlTextWriter oHtmlTextWriter = new                				System.Web.UI.HtmlTextWriter(oStringWriter);
             			ClearControls(dgrdExport);
				dgrdExport.RenderControl(oHtmlTextWriter);
				pg.Response.Write(oStringWriter.ToString());
				pg.Response.End();
			}
			catch(System.Exception ex)
			{
				throw ex;
			}

		}

Code For Clear Controls from form

private static void ClearControls(Control control)
		{
			for (int cnt=control.Controls.Count -1; cnt>=0; cnt--)
			{
				ClearControls(control.Controls[cnt]);
			}
			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;
		}