Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to convert gridview values to .xls file
Posted
Updated 14-Apr-12 1:42am
v2
Comments
uspatel 14-Apr-12 7:02am    
gridview to excel or excel to gridview
In window or Web?
Nelek 14-Apr-12 7:02am    
title changed to make it consistent (there was a repost confirmation)

C#
 protected void BindData()
    {
sqlcommand cmd=new sqlCommand("Select * from Emp");
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        gvdetails1.DataSource = ds.Tables[0];
        gvdetails1.DataBind();
    }
protected void Button1_Click(object sender, EventArgs e)
    {
        string attachment = "attachment; filename=export.xls;hdr=yes";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htm = new HtmlTextWriter(sw);
        HtmlForm frm = new HtmlForm();
        gvdetails1.Parent.Controls.Add(frm);
        frm.Attributes["Runat"] = "Server";
        frm.Controls.Add(gvdetails1);
        frm.RenderControl(htm);
        Response.Write(sw.ToString());
        Response.End();
    }
 
Share this answer
 
Comments
rajnish singh rathor 14-Apr-12 9:19am    
Dear Shweta
HtmlForm frm = new HtmlForm();
this line give error like
The type or namespace name 'HtmlForm' could not be found (are you missing a using directive or an assembly reference?)
rajnish singh rathor 14-Apr-12 9:19am    
which assembly require
shwetha1 16-Apr-12 4:59am    
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
Use these Namespaces it will works fine friend...
 
Share this answer
 

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