Skip to content

Instantly share code, notes, and snippets.

@kellerd
Last active October 23, 2015 15:30
Show Gist options
  • Save kellerd/5053467474a1e0e8e959 to your computer and use it in GitHub Desktop.
Save kellerd/5053467474a1e0e8e959 to your computer and use it in GitHub Desktop.
Code for failing to export to excel
<asp:Button ID="btnExportToExcel" runat="server" Text="Export to Excel"></asp:Button>
Private Sub btnExportToExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportToExcel.Click
Dim excelDatagrid = New DataGrid()
Try
''' Removed code for clairty to get data into datagrid
excelDatagrid.DataSource = New List(Of Employees)({New Employee With {.Name = "Dan"}})
excelDatagrid.DataBind()
Finally
''' Removed code for clairty to get data into datagrid
End Try
'Clear whatever is in the response buffer
Response.Clear()
Response.Buffer = True
'Prepare to send to an excel spreadsheet.
Response.ContentType = "application/vnd.ms-excel"
'Set the excel spreadsheet properties
Dim fileName As String = "inline;filename=TCNCI_Search_Recherche.xls"
Response.AddHeader("Content-Disposition", fileName)
Response.Charset = "UTF-8"
Response.ContentEncoding = System.Text.Encoding.Default
'Disable view state as we aren't passing by an HTTP request
'it's not necessary to preserve the state of the server controls
EnableViewState = False
'Write the datagrid to the Response buffer
Dim oStringWriter As System.IO.StringWriter = New System.IO.StringWriter
Dim oHtmlTextWriter As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(oStringWriter)
excelDatagrid.RenderControl(oHtmlTextWriter)
Response.Write(oStringWriter.ToString())
'Free up the resource used by the temporary datagrid
excelDatagrid.Dispose()
'Re-enable view state so the user can keep navigating as usual.
EnableViewState = True
Response.End()
End Sub
Public Class Employee
Public Property Name As String
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment