MansoorShaikh
MansoorShaikh

Reputation: 923

Faster export of datagridview with colored cells to excel

I have searched and could find only ways to export datagridview to excel without color information. I would like to export the datagridview to excel with the cells coloring intact. Right now, I do it cell by cell and it is very slow. I am looking for a faster way to do it?

Any suggestions or pointers would be really helpful.

Thanks Mansoor

Upvotes: 0

Views: 156

Answers (1)

Ron
Ron

Reputation: 1828

Public Shared Sub ExportGridViewToExcelGridView(ByVal Filename As String, ByRef gvr As GridView, ByRef currentPage As Page)

    Dim HtmlForm As System.Web.UI.HtmlControls.HtmlForm = New System.Web.UI.HtmlControls.HtmlForm()
    currentPage.Controls.Add(HtmlForm)
    HtmlForm.Controls.Add(gvr)
    currentPage.Response.Clear()
    currentPage.Response.Buffer = True
    currentPage.Response.AddHeader("Content-Disposition", "attachment; filename=" & Filename)
    currentPage.Response.ContentType = "application/vnd.ms-excel"
    currentPage.Response.ContentEncoding = System.Text.Encoding.UTF8
    currentPage.Response.Charset = ""
    currentPage.EnableViewState = False
    Using strwriter As New StringWriter
        Dim htmlwrt As HtmlTextWriter = New HtmlTextWriter(strwriter)
        HtmlForm.RenderControl(htmlwrt)
        htmlwrt.Flush()
        currentPage.Response.Write(strwriter.ToString)
        currentPage.Response.End()
    End Using
End Sub

you can use this function, make sure that you set EnableEventValidation to False in the page containing the gridview and the paging property is set to false..

Upvotes: 0

Related Questions