Remove Column using GridView to Export to Excel
I am binding a gridView to a List<model>
. I am able to export it to an excel file but I am not able to remove a specific column. Any Ideas on how do so? I tried gridView.Columns.RemoveAt(myIndex)
but didn't work and threw a null exception and I am assuming this 开发者_运维问答is because the gridView is not binded to a dataTable.
var models = new ModelService().List(startDate, DateTime.Now);
var gridView = new GridView { DataSource = models };
gridView.DataBind();
convert to a dataset or data table
foreach (GridViewRow dr in gridView.Rows)
{
//Create dataset and insert into cell value.
dr.Cells[0].Text;
dr.Cells[1].Text;
}
remove the desired rows
for (int j = ds.Tables[0].Rows.Count - 1; j >= 0; j--)
{
if (ds.Tables[0].Rows[j][column].ToString() == criteria)
{
ds.Tables[0].Rows.RemoveAt(j);
}
}
then export the dataset
Two suggestions:
- Use LINQ to select just the columns you want from your ModelService so that the columns you don't want never make it to the grid.
- Define your columns in the GridView and hide the ones you don't want when exporting to Excel. I do this anyway becuase I want more control over the formatting of the columns.
精彩评论