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

Export any page to Excel automatically

3.75/5 (4 votes)
24 Oct 2011CPOL 49.2K  
Export any page to Excel automatically
This is your base page, you can now call your page with ExcelExport=True in the query string to make the page export to Excel.

Keep in mind that you will have a popup message when opening in .xls because it is not in the correct format. However, it will display nicely in Excel in most cases. Some fancy HTML Ajax will break it slightly and in those cases you could strip it out manually in the render function.

Here is a version with embedded css.
http://www.codeproject.com/Tips/273221/Directly-embedding-CSS-or-strip-it-out-instead-of"
Note that if the popup is a problem, you can see my other Excel tip/trick. Clickety[^]


Here is how you can parse out controls you don't want to export to excel
Parse out controls from your html 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;

// <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 (HtmlTextWriter htmlWrite = new HtmlTextWriter(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.
        }
    }
}

License

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