Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Directly embedding .CSS ( or strip it out ) instead of href link (Excel export part 2)

0.00/5 (No votes)
24 Oct 2011CPOL 14.9K  
Directly embedding .CSS ( or strip it out ) instead of href link (Excel export part 2)
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.

/// <summary>
/// Summary description for ReportBase
/// </summary>
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)
        {
            //If the download link is pressed we will get a thread abort.
        }
    }
     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)
                {
                    //URL Rewrite
                    //string sStylesheetName = value;
                    //int iSlashPos = value.LastIndexOf("../");
                    //if (iSlashPos >= 0) sStylesheetName = value.Substring(iSlashPos + 3);
                    //value = VirtualPathUtility.ToAbsolute("~/" + sStylesheetName);
                    // CSS Embedding
                    WebRequest request = WebRequest.Create(HttpContext.Current.Server.MapPath(value));
                    // The credentials may be required if we get a 401.
                    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();
                        }
                    }
//Comment out this write to effectively just strip out the css
                    Write("></link><style TYPE=\"text/css\"> <!--" + cssResponse + "-->");
                    Context.Items[contextItemKey] = true;
                }
            }
            else
            {
                base.WriteAttribute(name, value, fEncode);
            }
        }
   }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)