Wednesday, 1 October 2008

Export to Excel using ASP.NET

I wanted to create a very simple excel export, from an asp.net 2.0 web application, that would take data and display it somewhat like this:



I used the following C# code. Which can be place within a LinkButton, or Button click event handler:

byte[] data = Encoding.UTF8.GetBytes("
Column 1Column 2
Data 1Data 2
Data 3Data 4
"); Response.Clear(); Response.ClearHeaders(); Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("content-disposition", "filename=test.xls"); Response.BinaryWrite(data); Response.End();


As you can see I've used an HTML table as the source of the data. You can also style this and Excel will display it correctly using any CSS you provide.

The name of the file is also set to "test.xls" using the header content-disposition.

No comments: