Click here to Skip to main content
15,867,453 members
Articles / Web Development / ASP.NET
Tip/Trick

Export any page to Excel automatically

Rate me:
Please Sign up or sign in to vote.
3.75/5 (4 votes)
24 Oct 2011CPOL 47.9K   10   4
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)


Written By
Software Developer (Senior)
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 1 2626 Pin
khanyasir1-Nov-11 20:23
khanyasir1-Nov-11 20:23 
GeneralRe: 2626? Pin
rj452-Nov-11 6:34
rj452-Nov-11 6:34 
GeneralReason for my vote of 5 Thanks for this nice article. Pin
Member 432084425-Oct-11 10:33
Member 432084425-Oct-11 10:33 
GeneralYou forgot to mention the URL for your other Tip/Trick. I th... Pin
thatraja21-Oct-11 18:48
professionalthatraja21-Oct-11 18:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.