Suppose you have grid with ID
GridView1 and it contains two columns. And you want to export only first column then find below code:
private void btnExportExcel_Click()
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=MyData.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[0].Visible = True;
GridView1.HeaderRow.Cells[1].Visible = False;
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
GridViewRow row = GridView1.Rows[i];
row.Cells[0].Visible = True;
row.Cells[1].Visible = False;
row.BackColor = System.Drawing.Color.White;
row.Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
}
Here I have hard coded(True/False) and if you need it dynamic then you ad checkboxes to side of the column and onchange of checkbox store it in viewstate. Later you can fetch checked columns from view state.
http://www.aspsnippets.com/Articles/ASP.Net-GridView-Export-only-selected-columns-to-Excel-Sheet.aspx[
^]