I've enabled exporting to Excel from a GridView like this :
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "BU Results" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
GridView1.GridLines = GridLines.Both;
GridView1.HeaderStyle.Font.Bold = true;
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}
protected void Button3_Click(object sender, EventArgs e)
{
ExportGridToExcel();
}
This works fine- the only issue is that when I have paging enabled it exports only one page at a time and includes the page hyperlinks at the bottom.
So I tried fixing it by adding this code to my ExportGridToExcel :
GridView1.AllowPaging = false;
GridView1.DataBind();
This does get rid of the paging in the export, however I've also got some filters applied and those are then removed in the Export so it exports the whole GridView Table rather than the filtered Data.
This is how the GridView can be filtered :
protected void Button1_Click(object sender, EventArgs e)
{
ViewState.Add("test", true);
if (DropDownList1.SelectedValue.ToString() == "Name")
{
ObjectDataSource1.FilterExpression = "Name LIKE '%" + TextBox1.Text + "%' ";
}
else if (DropDownList1.SelectedValue.ToString() == "Department")
{
ObjectDataSource1.FilterExpression = "Department LIKE '%" + TextBox1.Text + "%' ";
}
}
Any suggestions?