Export grid to excel
this code deals with exporting gridview to excel and pdf
This code deals with Converting the contents of the grid view to excel and pdf and the following ways makes it desirable
TO EXPORT GRID:
Private Sub ExportGridView()
Dim attachment As String = "attachment;filename=Countrylist.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/ms-excel"
Dim sw As StringWriter = New StringWriter()
Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
GridView1.RenderControl(htw)
Response.Write(sw.ToString())
Response.[End]()
End Sub
TO Export to different application change the content-type
the above code might result in an HTTP Exception to avoid this use this
public override void VerifyRenderingInServerForm(Control control)
{
}
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.IO
Public Partial Class Default6
Inherits System.Web.UI.Page
Private connection As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Private da As SqlDataAdapter = New SqlDataAdapter()
Private ds As DataSet = New DataSet()
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
BindGrid()
End Sub
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim con As SqlConnection = New SqlConnection(connection)
con.Open()
Dim cmd As SqlCommand = New SqlCommand("insert into Country values('" + TextBox1.[Text] + "','" + TextBox2.[Text] + "')", con)
cmd.ExecuteNonQuery()
con.Close()
BindGrid()
End Sub
Private Sub BindGrid()
Dim con As SqlConnection = New SqlConnection(connection)
con.Open()
da = New SqlDataAdapter("Select * from Country", con)
da.Fill(ds)
GridView1.DataSource = ds
GridView1.DataBind()
con.Close()
End Sub
Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub
Private Sub ExportGridView()
Dim attachment As String = "attachment; filename=Countrylist.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/ms-excel"
Dim sw As StringWriter = New StringWriter()
Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
GridView1.RenderControl(htw)
Response.Write(sw.ToString())
Response.[End]()
End Sub
Protected Sub btnExcel_Click(ByVal sender As Object, ByVal e As EventArgs)
GridView1.Columns(2).Visible = False
GridView1.Columns(3).Visible = False
ExportGridView()
End Sub
Private Sub clear()
TextBox1.[Text] = String.Empty
TextBox2.[Text] = String.Empty
btnSave.Enabled = True
End Sub
Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As EventArgs)
Me.clear()
End Sub
End Class