Search code examples
asp.netvb.netexport-to-excel

Is it possible to export a sql table to excel using asp.net


I have a webpage with an export button. Is it possible to export a sql table to excel when this button is pressed? I can do it with a gridview but would just like a simple button with code behind to do the work. Can someone point me in the direction I need?


Solution

  • If you want it in excel you can use the following code. Select the data and put it in a Gridview and do the following.

    Dim GridView1 As New GridView
    
    SqlDataSource1.SelectCommand = "SELECT * FROM TableName"
    GridView1.DataSource = SqlDataSource1
    GridView1.DataBind()
    
    Response.Clear()
    Response.Buffer = True
    Response.ContentType = "application/vnd.ms-excel"
    Response.Charset = ""
    Me.EnableViewState = False
    Dim oStringWriter As New System.IO.StringWriter
    Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)
    
    GridView1.RenderControl(oHtmlTextWriter)
    
    Response.Write(oStringWriter.ToString())
    Response.End()
    

    You can also format the Gridview to make it look good on the Excel Sheet.