Menu

Want to work with us? We're on the lookout for a talented Digital Project Manager.

We're hiring

Export Datatable to Excel

Web Bureau


17 December 2010 by Web Bureau

To follow up on my last post this is code to export any datatable to excel.

Public Shared Function Export_Excel(ByVal dt As DataTable, ByVal filename As String) As String

        Dim message As String = Nothing

        Dim tw As New System.IO.StringWriter
        Dim hw As New System.Web.UI.HtmlTextWriter(tw)

        Try
            Dim dg As DataGrid = New DataGrid
            dg.DataSource = dt
            dg.DataBind()

            Dim context As HttpContext = HttpContext.Current

            context.Response.Clear()
            context.Response.AddHeader("content-disposition", "attachment;filename=" & filename & ".xls")
            context.Response.ContentType = "application/vnd.ms-excel"
            context.Response.Charset = ""

            dg.RenderControl(hw)

            context.Response.ContentEncoding = System.Text.Encoding.Unicode
            context.Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble())
            context.Response.Write(tw.ToString())
            context.Response.End()

            message = "Export Successful"

        Catch ex As Exception

            message = ex.Message.ToString

        End Try

        Return message

    End Function

Grow your businessStart a project with us today.