Fast, Short and Easy way to generate gridview to excel. You can also get rid of unnessary controls like check box, button, and select link etc, but you can if you want to.
Please enjoy the code below:
Please enjoy the code below:
private void ExportToExcel()
{
string attachment = "attachment; filename=statement.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView newGrid = new GridView();
//if you want to copy old gridview column
//DataControlFieldCollection columns = OldGridView.Columns;
//foreach (DataControlField col in columns)
//{
// newGrid.Columns.Add(col);
//}
newGrid.DataSource = SqlDataSource1.Select(DataSourceSelectArguments.Empty) as DataView;
newGrid.DataBind();
newGrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}