How to export Gridview to MS-Excel ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Shreeharsha B R
    New Member
    • Jan 2011
    • 2

    How to export Gridview to MS-Excel ?

    Hi to all technical friends,...

    I have one application in ASP.NET. In that I have used Gridview. I want convert it to MS-Excel Format. I wrote the code as below.
    Code:
    protected void BindData()
    {
       SqlConnection con=new SqlConnection("harsha");
       SqlDataAdapter da=new SqlDataAdapter('Query',con);
       DataSet ds=new DataSet();
       da.Fill(ds);
       GridView1.DataSource=ds;
       GridView1.DataBind();
    }
    And I called it in page_load()

    And wrote code for Export button as below
    Code:
    protected void Button1_Click(object sender, EventArgs e)
    Response.Clear();
                Response.AddHeader("content-deposition", "attachment;FileName=xyz.xls");
                Response.ContentType = "application/vnd.xlsx";
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                GridView1.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.End();
    }
    And add another function as
    Code:
    public override void VerifyRenderingInServerForm(Control control)
    {            
    }
    I don't get any error. But I am not getting the Excel document. Can you please suggest where I was wrong..

    thanks in advance
    Last edited by Frinavale; Dec 1 '11, 02:56 PM. Reason: Removed bold, italic and underlining from the question. Added code tags.
Working...