Total Pageviews

Thursday, March 28, 2013

ASP.Net Download Data in Excel File without using interop.

ASP.Net  Download Data in Excel File  without using interop.
Use following code to download data as excel. First you should bind your data to gridview .


Sub saveExcel()
        ' Change the Header Row back to white color
        GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF")

        ' This loop is used to apply stlye to cells based on particular row
        For Each gvrow As GridViewRow In GridView1.Rows
            gvrow.BackColor = Drawing.Color.White

            If gvrow.Cells(4).Text = "True" Then
                gvrow.BackColor = Drawing.Color.Yellow
                'For k As Integer = 0 To gvrow.Cells.Count - 1
                '    gvrow.Cells(k).Style.Add("background-color", "#EFF3FB")
                'Next
            End If
        Next

        Response.ClearContent()

        Response.AddHeader("content-disposition", "attachment; filename=GridViewToExcel.xls")

        Response.ContentType = "application/excel"

        Dim sWriter As New System.IO.StringWriter()

        Dim hTextWriter As New HtmlTextWriter(sWriter)

        GridView1.RenderControl(hTextWriter)

        Response.Write(sWriter.ToString())

        Response.End()
        lblMsg.Text = "Excel created"

        'GridView1.RenderControl(htw)

    End Sub

- Written By 
Vinod Kotiya

No comments: