steps:
-Override Render on your page ( In this excel export example we do this in a base class )
-Go through all the controls with Findcontrols and find the control type your looking for
-Render specific controls to a list of strings
-render page to string
-remove specific controls html from page.
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Threading;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.Text;
public class ReportBase : Page
{
const string ExcelExport = "ExcelExport";
public ReportBase()
{
this.Load += new EventHandler(ReportBase_Load);
}
void ReportBase_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session.Add(ExcelExport, Request.QueryString[ExcelExport]);
}
}
protected override void Render(HtmlTextWriter writer)
{
if (Session[ExcelExport] != null && bool.Parse(Session[ExcelExport].ToString()))
{
List<Control> flatList = Utilities.FindControls(this);
List<string> removeList = new List<string>();
foreach (Control item in flatList)
{
if (item.GetType() == typeof(Image))
{
removeList.Add(RenderControlToHtmlString(item));
}
}
StringBuilder html = null;
using (System.IO.StringWriter stringWrite = new System.IO.StringWriter())
{
using (HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite))
{
base.Render(htmlWrite);
html = new StringBuilder(stringWrite.ToString());
}
}
foreach (var item in removeList)
{
html.Replace(item, String.Empty);
}
Download(html.ToString());
}
else
{
base.Render(writer);
}
}
public void Download(string text)
{
try
{
HttpResponse response = Page.Response;
response.Clear();
response.Write(text);
response.Flush();
response.End();
}
catch (ThreadAbortException)
{
}
}
public static string RenderControlToHtmlString(Control ctrl)
{
StringBuilder sb = new StringBuilder();
StringWriter tw = new StringWriter(sb);
HtmlTextWriter hw = new HtmlTextWriter(tw);
ctrl.RenderControl(hw);
return sb.ToString();
}