24 Dec 2015

Export to Excel ASP.NET

 
 DateTime currentDtTime = DateTime.Now;
 string filename = e.CommandName + "_Records_" + currentDtTime.Year + "" + currentDtTime.Month + "" + currentDtTime.Day + "_" + currentDtTime.Hour + "" + currentDtTime.Minute + "" + currentDtTime.Second + ".xls";
 using (System.IO.StringWriter sw = new System.IO.StringWriter()){
     using (HtmlTextWriter htw = new HtmlTextWriter(sw)){
  // instantiate a datagrid
  GridView dg = new GridView();
  String QueryToExport = "";
  SqlDataAdapter DARecordsToExport = new SqlDataAdapter(QueryToExport, new SqlConnection([Connection String]));
  DataSet DSRecordsToExport = new DataSet();
  DARecordsToExport.Fill(DSRecordsToExport);
  for (int ColumnIndex = 0; ColumnIndex < DSRecordsToExport.Tables[0].Columns.Count; ColumnIndex ++){
      if (TypeCode.Boolean == Type.GetTypeCode(DSRecordsToExport.Tables[0].Columns[ColumnIndex].DataType)){
   DSRecordsToExport.Tables[0].Columns.RemoveAt(ColumnIndex);
   ColumnIndex--;
      }
  }
  dg.DataSource = DSRecordsToExport;
  dg.DataBind();
  dg.RenderControl(htw);
  Response.ClearContent();
  Response.ContentType = "application/vnd.ms-excel";
  Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
  Response.Write(sw.ToString());
  Response.End();
     }
 }

No comments:

Post a Comment