This is an example of how to export to Excel, but also we inject the .css in an embedded way rather than using href links which can fail depending on your server environment.
It css href links can also fail if you are doing certain types of URL rewriting although this is not generally for URL rewriting.
This also shows a good way to strip out.
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()))
{
using (System.IO.StringWriter stringWrite = new System.IO.StringWriter())
{
using (RewriteLinkHtmlTextWriter htmlWrite = new RewriteLinkHtmlTextWriter(stringWrite))
{
base.Render(htmlWrite);
DownloadExcel(stringWrite.ToString());
}
}
}
else
{
base.Render(writer);
}
}
public void DownloadExcel(string text)
{
try
{
HttpResponse response = Page.Response;
response.Clear();
response.AddHeader("cache-control", "must-revalidate");
response.ContentType = "application/vnd.ms-excel";
response.Write(text);
response.Flush();
response.End();
}
catch (ThreadAbortException)
{
}
}
public class RewriteLinkHtmlTextWriter : HtmlTextWriter
{
#region Constructors
public RewriteLinkHtmlTextWriter(HtmlTextWriter writer) : base(writer)
{
this.InnerWriter = writer.InnerWriter;
}
public RewriteLinkHtmlTextWriter(System.IO.TextWriter writer) : base(writer)
{
this.InnerWriter = writer;
}
#endregion
public override void WriteAttribute(string name, string value, bool fEncode)
{
if (name == "href")
{
HttpContext Context = HttpContext.Current;
string contextItemKey = value + "HrefAlreadyWritten";
if (Context.Items[contextItemKey] == null)
{
WebRequest request = WebRequest.Create(HttpContext.Current.Server.MapPath(value));
request.Credentials = CredentialCache.DefaultCredentials;
string cssResponse = String.Empty;
using (WebResponse webresponse = request.GetResponse())
{
using (Stream dataStream = webresponse.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
cssResponse = reader.ReadToEnd();
}
}
Write("></link><style TYPE=\"text/css\"> <!--" + cssResponse + "-->");
Context.Items[contextItemKey] = true;
}
}
else
{
base.WriteAttribute(name, value, fEncode);
}
}
}
}