kresa kresa - 6 months ago 51
Vb.net Question

Simple export from ASP.NET GridView into Excel VB.NET

I have a GridView that I need to export into Excel (by button event) and I'm using Visual Studio and vb.net.

I never tried this before and I'm kinda clueless, is there a simple way to do this? I don't think I need any complications at the moment, just a simple export of the GridView information.

Also I already got a connection between the GridView and my database. I tried adding a working Excel export from other project but I still miss something .

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Verifies that the control is rendered

End Sub

Protected Sub exportExelBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles exportExelBtn.Click
Dim errorCheck As Integer = 0
Dim popupscript As String = ""

If approvalGrid.Rows.Count > 0 Then
Try

Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "TestPage.xls"))
Response.ContentEncoding = Encoding.UTF8
Response.ContentType = "application/ms-excel"
' Dim sw As New stringwriter()
Dim tw As New IO.StringWriter()
Dim htw As New HtmlTextWriter(tw)
approvalGrid.RenderControl(htw)
Response.Write(tw.ToString())
Response.[End]()

Catch ex As Exception
errorCheck = 1
End Try
Else
errorCheck = 1
End If
If errorCheck = 1 Then
'a pop up error messege feature
popupscript = "<script language='javascript'>" + "alert(" + Chr(34) + "There was an error in exporting to exel, please make sure there is a grid to export!" + Chr(34) + ");</script>"
End If
Page.ClientScript.RegisterStartupScript(Me.GetType(), "PopUpWindow", popupscript, False)
End Sub


The problem is that the file that it creates upon click says it's not Excel format and when I agree to open it I do see the GridView information as I wanted but I also see a lot of extra info in the form of buttons calanders and other stuff from my page, how can I prevent the export of those other stuff?

Answer

Please Try Below code

Public Overrides Sub VerifyRenderingInServerForm(control As Control)
        ' Verifies that the control is rendered 

End Sub

Protected Sub btnExport_Click(sender As Object, e As EventArgs)
    If gridview.Rows.Count > 0 Then
        Try
            gridview.Columns(0).Visible = False
            Response.ClearContent()
            Response.Buffer = True
            Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "TestPage.xls"))
            Response.ContentEncoding = Encoding.UTF8
            Response.ContentType = "application/ms-excel"
            Dim sw As New StringWriter()
            Dim htw As New HtmlTextWriter(sw)
            gridview.RenderControl(htw)
            Response.Write(sw.ToString())
            Response.[End]()

        Catch ex As Exception
        Finally
            gridview.Columns(0).Visible = True
        End Try
    End If
End Sub
Comments