Link to home
Start Free TrialLog in
Avatar of Fidelisme
Fidelisme

asked on

Export from Datagrid to Excel

Hi Guys,

I have some Info in Datagrid that i need to export to Excel.
I'm Using VB.net 2005 and placed a datagridView on a form.

How can i export the content of my grid to excel ??

Thanks.
Avatar of Artform04
Artform04

heya,

Ye its possible, i did it recently in a b.net 2003 app. The class code (datagrid to excel) should still work... its below...


call it using:

dim objDGtoExcel as new DatagridToExcel
objDGtoExcel .DataGridToExcel(yourdatagrid, Response)


class:

Public Class DatagridToExcel

    Public Shared Sub DataGridToExcel(ByVal dgExport As DataGrid, ByVal response As HttpResponse)
        'clean up the response.object
        response.Clear()
        response.Charset = ""
        'set the response mime type for excel
        response.ContentType = "application/vnd.ms-excel"
        'create a string writer
        Dim stringWrite As New System.IO.StringWriter
        'create an htmltextwriter which uses the stringwriter
        Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite)

        'instantiate a datagrid
        Dim dg As New DataGrid
        ' just set the input datagrid = to the new dg grid
        dg = dgExport

        ' I want to make sure there are no annoying gridlines
        dg.GridLines = GridLines.None
        ' Make the header text bold
        dg.HeaderStyle.Font.Bold = True

        ' If needed, here's how to change colors/formatting at the component level
        'dg.HeaderStyle.ForeColor = System.Drawing.Color.Black
        'dg.ItemStyle.ForeColor = System.Drawing.Color.Black

        Try
            'bind the modified datagrid
            dg.DataBind()
            'tell the datagrid to render itself to our htmltextwriter
            dg.RenderControl(htmlWrite)
            'output the html
            response.Write(stringWrite.ToString().Replace(" ", Chr(13)))

            'response.End()
            HttpContext.Current.ApplicationInstance.CompleteRequest()
        Catch ex As Exception
            Dim err As String = ex.ToString
        End Try
    End Sub

End Class




** Phil **
ASKER CERTIFIED SOLUTION
Avatar of Gruff82
Gruff82

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial