Export excel data from web user control's gridview in VB.net and ASP.net

Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 1462
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">

<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<RowStyle BackColor="#EFF3FB" />

<EditRowStyle BackColor="#2461BF" />

<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

<AlternatingRowStyle BackColor="White" />



<br />

<asp:Button ID="Button1" runat="server" Font-Bold="True" OnClick="Button1_Click"

Text="Export To Excel" />

and in code behind:-

Protected Sub Page_Load(sender As Object, e As EventArgs)

If Not Page.IsPostBack Then

GridView1.DataSource = BindData()

End If

End Sub

Private ReadOnly Property ConnectionString() As String

Return "<SQL Data Source>"
End Get
End Property

Private Function BindData() As DataSet

' make the query

Dim query As String = "SELECT * FROM tblTest"

Dim myConnection As New SqlConnection(ConnectionString)

Dim ad As New SqlDataAdapter(query, myConnection)

Dim ds As New DataSet()

ad.Fill(ds, "TestTable")

Return ds

End Function

Protected Sub Button1_Click(sender As Object, e As EventArgs)


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

Response.Charset = ""

Response.ContentType = "application/vnd.xls"

Dim stringWrite As New System.IO.StringWriter()

Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)




End Sub

Public Overrides Sub VerifyRenderingInServerForm(control As Control)

' Confirms that an HtmlForm control is rendered for the

'specified ASP.NET server control at run time.

End Sub

Comments or Responses

Login to post response