Home DotNet Export DataTable to Excel via DataGrid in ASP.NET
Author:

Here's how you can quickly export a DataTable to an Excel file in ASP.NET using the DataGrid control. User can then save the file to their computer.

Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnExport.Click
        Response.ClearContent()
        Response.Buffer = True
        Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", "EquipmentList_" + DateTime.Now.ToString("dd-MM-yyyy-hhmm")))
        Response.ContentType = "application/vnd.xls"
        Response.Charset = ""

        Dim stringWrite As StringWriter = New StringWriter
        Dim htmlWrite As HtmlTextWriter = New HtmlTextWriter(stringWrite)
        Dim dg As DataGrid = New DataGrid
        Dim dt As DataTable
        Dim oEquipment As clsEquipment = New clsEquipment

        dt = oEquipment.GetEquipmentList(False).Tables(0)
        dt.Columns.Remove("ViewInd")
        dt.Columns.Remove("ParentEquipmentID")
        dt.Columns.Remove("SiteID")

        dg.DataSource = dt
        dg.DataBind()
        dg.RenderControl(htmlWrite)

        Response.Write(stringWrite.ToString())
        Response.End()
End Sub



Comments (0)
Write comment
Your Contact Details:
Comment:
Security
Please input the anti-spam code that you can read in the image.

"