Click here to Skip to main content
15,904,828 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i would like to show gridview data in microsoft office excel-2007,but it is automatically opening in Visual studio any one tell me

below my code..

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Collections;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Configuration;
using System.IO;

public partial class Gridview_to_excel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        bindgrid();
    }

    private void bindgrid()
    {
        SqlConnection con = new SqlConnection("Data Source=........;Initial Catalog=.....;Integrated Security=True");
        SqlDataAdapter da = new SqlDataAdapter("select * from gridview", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        
    }
    protected void btnexcel_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AddHeader("content-dispotion", "attachment;filename=myexcelfile.xls");
        Response.ContentType = "applicaton/vnd.xls";
        StringWriter sw = new StringWriter();
        HtmlTextWriter tw = new HtmlTextWriter(sw);
        GridView1.RenderControl(tw);
        Response.Write(sw.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
      
    }
}
Posted
Updated 29-Mar-12 2:08am
v2
Comments
[no name] 29-Mar-12 8:08am    
<pre> tag added.
rockpune 29-Mar-12 8:37am    
filename= .xls what file name i have to give there
ZurdoDev 29-Mar-12 8:17am    
Are you saying the .xls file is opening within Visual Studio?
rockpune 29-Mar-12 8:37am    
yes filename= .xls what file name i have to give there
ZurdoDev 29-Mar-12 8:54am    
When you are presented with a dialog that asks if you want to open or save a file and you click open it uses your Windows file associations to open it. So, if you are saying it actually opens the Excel file in Visual Studio instead of Excel that means you have .xls registered to Visual Studio on your Windows machine.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900