65.9K
CodeProject is changing. Read more.
Home

Export Selected Rows Only to Excel

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (2 votes)

Jul 29, 2011

CPOL
viewsIcon

28879

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.