Friday, August 2, 2013

export gridview data directly to excel file

To export gridview to excel in asp.net

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