Click here to Skip to main content
15,884,298 members
Articles / Web Development / ASP.NET
Tip/Trick

Export Selected Rows Only to Excel

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
29 Jul 2011CPOL 28.4K   5   2
How to export selected rows of a GridView to Excel.
Export Selected Rows Only to Excel

First just create your gridview and bind it and add checkbox column to your gridview i am not going in depth.

Put one button called EXPORT and on page and write following code in that.

view source print?
01	DataTable dt = new DataTable();
02	        dt.Columns.Add("empid");
03	        dt.Columns.Add("empname");           
04	        foreach (GridViewRow row in GridView1.Rows)
05	        {
06	            CheckBox chk = (CheckBox)row.FindControl("CheckBox1");
07	            if (chk.Checked == true)
08	            {
09	              int i = row.RowIndex;
10	              Label lbl = (Label)GridView1.Rows[i].FindControl("Label1");
11	              Label lbl1 = (Label)GridView1.Rows[i].FindControl("Label2");
12	              DataRow dr = dt.NewRow();
13	              dr["empid"] = Convert.ToString(lbl.Text);
14	              dr["empname"] = Convert.ToString(lbl1.Text);
15	              dt.Rows.Add(dr);
16	            }
17	        }
18	        GridView GridView1= new GridView()
19	        GridView1.DataSource = dt;
20	        GridView1.DataBind();
21	        Response.Clear();
22	        Response.Buffer = true;
23	        Response.ContentType = "application/ms-excel";
24	        Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "selectedrows"));
25	        Response.Charset = "";
26	        System.IO.StringWriter stringwriter = new StringWriter();
27	        HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
28	        gd.RenderControl(htmlwriter);
29	        Response.Write(stringwriter.ToString());
30	        Response.End();

I am making datatable, gridview runtime and will bind that gridview with datatable.

License

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


Written By
Web Developer Cholamandalam MS General Insurance
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionExcellent! Pin
Member 959977726-Nov-12 7:29
Member 959977726-Nov-12 7:29 
GeneralReason for my vote of 4 Nice Pin
anil_cisc1-Aug-11 17:54
anil_cisc1-Aug-11 17:54 
Reason for my vote of 4
Nice

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.