Saving an Excel file to a user’s machine from ASP.NET page

Want a super-simple way to allow users to save data as an Excel file on their local machine through ASP.NET? There is a nice article at http://www.developer.com/net/asp/article.php/3633891/ASPNET-Tip-Exporting-Data-to-Excel.htm.

I’ll be even simpler. First, you clear out all the HTML code from the aspx page, so that only the @Page tag remains:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExcelTest.aspx.cs" Inherits="TestSite.ExcelTest" %>

Yep, that’s the entire aspx page.

The code-behind file is equally simple. Just add the Response.ContentType tag, and a table to hold the Excel data:

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "application/vnd.ms-excel";
            Response.Write("<table><tr><td>1</td><td>2</td><td>3</td></tr><tr><td>1</td><td>2</td><td>3</td></tr></table>");
        }

When the user hits the page, they will prompted to open or save our Excel file filled with incredibly useful data.

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: