Monday, October 13, 2008

Export Data From DataGrid To Excel

DataGrid.AllowPaging = false; //cancel paging if there is

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=" + "FileNameToExportIn");
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
ClearControls(DataGrid);
DataGrid.AllowPaging = false;

DataGrid.DataSource=ds; //Bind Grid Again
DataGrid.DataBind();


//To Show Grid Lines
DataGrid.GridLines = GridLines.Both;

//To Format Header With Color
DataGrid.HeaderStyle.BackColor = System.Drawing.Color.LightGray;

DataGrid.RenderControl(htw);
DataGrid.AllowPaging = true;
DataGrid.DataSource=ds; //Bind Grid Again
DataGrid.DataBind();


Response.Write(sw.ToString());
Response.End();

DataGrid.AllowPaging = true;

No comments: