title: ASP.Net Grid Export to Excel
body: <p>I am using following code to export my <code>GridView</code> to <code>Excel</code>:</p>
  
  <pre><code>string attachment = "attachment; filename=Contacts.xls";
  Response.ClearContent();
  Response.AddHeader("content-disposition", attachment);
  Response.ContentType = "application/ms-excel";
  StringWriter sw = new StringWriter();
  HtmlTextWriter htw = new HtmlTextWriter(sw);
  gvReports.RenderControl(htw);
  Response.Write(sw.ToString());
  Response.End();
  </code></pre>
  
  <p>This code is copied from <a href="http://www.c-sharpcorner.com/UploadFile/DipalChoksi/exportxl_asp2_dc11032006003657AM/exportxl_asp2_dc.aspx" rel="nofollow">this</a> site. I have followed all the instructions but after executing nothing happened. No exception (Except <code>Thread.Abort</code> which is, I think, because of <code>Response.End()</code>). </p>
  
  <p>I have also used <code>Response.Flush()</code> BUT nothing is happening no exception or file etc.</p>
  
  <p>Thanks.</p>
  
  <p><strong>EDIT Now Code Is like following:</strong></p>
  
  <p>My GridView is in Control. The control is on asp.net page and that page has following method.</p>
  
  <pre><code>public override void VerifyRenderingInServerForm(Control control)
  {
  
  }
  </code></pre>
  
  <p>Click event of button in ascx control:</p>
  
  <pre><code>protected void btnExportToExcel_Click(object sender, EventArgs e)
  {
    ExportToExcel();
  }
  
  private void ExportToExcel()
  {
      Response.Clear();
      Response.Buffer = true;
      Response.AddHeader("content-disposition",
        "attachment;filename=GridViewExport.xls");
      Response.Charset = "";
      Response.ContentType = "application/vnd.ms-excel ";
      StringWriter sw = new StringWriter();
      HtmlTextWriter hw = new HtmlTextWriter(sw);
      gvReports.AllowPaging = false;
      gvReports.DataBind();
      gvReports.RenderControl(hw);
      Response.Output.Write(sw.ToString());
      Response.Flush();
      Response.End();
  }
  </code></pre>
  
  <p>gvReports has no link, checkbox etc. 5 bound columns and 1 button.</p>
  
  <p>Nothing is happening.</p>