title: Export GridView to Excel (not working)
body: <p>I've spent the last two days trying to get some bloody data to export to Excel. After much research I determined that the best and most common way is using <code>HttpResponse</code> headers as shown in my code below. After stepping through countless times in debug mode, I have confirmed that the data is in fact there and both filtered and sorted the way I want it. However, it does not download as an Excel file, or do anything at all for that matter.</p>
  
  <p>I suspect this may have something to do with my <code>UpdatePanel</code> or perhaps the <code>ImageButton</code> not posting back properly, but I'm not sure. What am I doing wrong? Please help me to debug this issue. I will be eternally grateful. Thank you. :)</p>
  
  <p><strong>Markup</strong></p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;asp:UpdatePanel ID="statusUpdatePanel" runat="server" UpdateMode="Conditional"&gt;
  &lt;Triggers&gt;
      &lt;asp:AsyncPostBackTrigger ControlID="btnExportXLS" EventName="Click" /&gt;
  &lt;/Triggers&gt;
  &lt;ContentTemplate&gt;
      &lt;asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="10"
          AllowSorting="True" DataSourceID="GridView1SDS" DataKeyNames="ID"&gt;
      &lt;/asp:GridView&gt;
      &lt;span&gt;&lt;asp:ImageButton ID="btnExportXLS" runat="server" /&gt;&lt;/span&gt;
  &lt;/ContentTemplate&gt;
  &lt;/asp:UpdatePanel&gt;
  </code></pre>
  
  <p><strong>Codebehind</strong></p>
  
  <pre class="lang-vb prettyprint-override"><code>Protected Sub ExportToExcel() Handles btnExportXLS.Click
      Dim dt As New DataTable()
      Dim da As New SqlDataAdapter(SelectCommand, ConnectionString)
  
      da.Fill(dt)
  
      Dim gv As New GridView()
      gv.DataSource = dt
      gv.DataBind()
  
      Dim sw As New IO.StringWriter()
      Dim hw As New System.Web.UI.HtmlTextWriter(sw)
      Response.ContentType = "application/vnd.ms-excel"
      Response.AddHeader("content-disposition", "attachment;filename=Report.xls")
      Response.Charset = String.Empty
  
      gv.RenderControl(hw)
      Response.Write(sw.ToString()) 'sw is a valid html table, but no Excel file downloads. :(
      Response.End()
  End Sub
  </code></pre>