Wednesday 23 July 2014

DataTable To Excel in VB.NET

  Public Sub ExportToExcel(ByVal dt As DataTable)
        If dt.Rows.Count > 0 Then
            Dim filename As String = "DownloadMobileNoExcel.xls"
            Dim tw As System.IO.StringWriter = New System.IO.StringWriter()
            Dim hw As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(tw)
            Dim dgGrid As DataGrid = New DataGrid()
            dgGrid.DataSource = dt
            dgGrid.DataBind()

            'Get the HTML for the control.
            dgGrid.RenderControl(hw)
            'Write the HTML back to the browser.
            'Response.ContentType = application/vnd.ms-excel;
            Response.ContentType = "application/vnd.ms-excel"
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "")
            Me.EnableViewState = False
            Response.Write(tw.ToString())
            Response.End()
        End If
    End Sub