I have one function that has to be put into practice.
Grid data is being bound to an excel export, and everything is going OK. However, I now need to hide the columns in the Excel export because of a new need. The option to UN-hide the columns that were hidden by code should thereafter be available to the user when he opens the Excel page.
Edit:
I am exporting a grid view control from my.aspx page to Excel using the code below:
public static void Export(string filename, GridView grid)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition",
string.Format("attachment; filename={0}", filename.Replace(" ", "") + ".xls"));
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.HeaderStyle.BackColor = System.Drawing.Color.Cyan;
GridViewRow row = new GridViewRow(0, 1, DataControlRowType.DataRow, DataControlRowState.Normal);
TableCell cell = new TableCell();
cell.Text = String.Format("{0}", Heading[count]);
cell.ColumnSpan = grid.Rows[1].Cells.Count;
cell.Attributes.Add("style", "background-color: white; color: black;text-align:left;");
cell.Attributes.Add("class", "yellow");
row.Cells.Add(cell);
grid.Controls[0].Controls.AddAt(0, row);
grid.RenderControl(htw);
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn(" ", typeof(String)));
dr = dt.NewRow();
dr[0] = " ";
dt.Rows.Add(dr);
GridView gvSpace = new GridView();
gvSpace.DataSource = dt;
gvSpace.GridLines = 0;
gvSpace.DataBind();
gvSpace.RenderControl(htw);
grid.HeaderStyle.BackColor = System.Drawing.Color.Cyan;
HttpContext.Current.Response.Write(@"<style> .sborder { color : Black;border : 1px Solid Black; } .yellow {background-color:yellow;color:black;} </style> ");
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
}
Before the gridview is exported to Excel, some columns must be hidden (in RowDataBound or a related event), and the user who exported the file must be able to reveal the hidden columns once the file has been opened in Microsoft Excel. The column is hidden in the grid view because it is rendered as HTML, but I am unable to make it visible in Microsoft Excel.