Wednesday, July 3, 2013

asp.net - how to export gridview values to excel in asp.net

to export a gridview to excel using asp.net,
following code will helpout

Protected Sub ExportToExcel()
        Try
            Dim stringWrite As StringWriter
            Dim htmlWrite As HtmlTextWriter
            Dim frm As HtmlForm = New HtmlForm()
            Dim style As String = "<style>td{ mso-number-format: \@; }</style>"
            Response.ClearHeaders()
            Response.AppendHeader("content-disposition", "attachment;filename=TEST.xls")
            Response.Charset = String.Empty '""
            Response.ContentType = "application/vnd.ms-xlsx"
            stringWrite = New StringWriter
            htmlWrite = New HtmlTextWriter(stringWrite)
            Controls.Add(frm)
            frm.Controls.Add(gvReport)
            frm.RenderControl(htmlWrite)
            Response.Write(style)
            Response.Write(stringWrite.ToString())
            Response.End()
        Catch ex As Exception
            WebMessage(ex.ToString)
        End Try
    End Sub

No comments:

Post a Comment