The simplest way to export data to Microsoft Excel using ASP.NET is to make a tab- and line break delimited string (CSV), which is written out to the client using a HTTP-Handler with the content type set to “application/vnd.ms-excel”.
1. Start by right clicking your project, choose “Add New Item”, then “Generic Handler”, give it the name “ExportToExcel.ashx”.
2. Add the following code:
<%@ WebHandler Language="C#" Class="ExportToExcel" %>
using System;
using System.Web;
public class ExportToExcel : IHttpHandler
{
private HttpContext _context;
public void ProcessRequest(HttpContext context)
{
_context = context;
// Set HTTP-header.
context.Response.Clear();
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("content-disposition", "attachment;filename=Fruits.xls");
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
// Output data.
OutputRow("Id", "Fruit", "Color");
OutputRow("1", "Banana", "Yellow");
OutputRow("2", "Watermelon", "Red");
OutputRow("3", "Grapes", "Lilac");
// Finished.
context.Response.End();
}
/// <summary>
/// Outputs 3 tab separated columns per row.
/// </summary>
protected void OutputRow(string col1, string col2, string col3)
{
_context.Response.Write(col1 + Convert.ToChar(9));
_context.Response.Write(col2 + Convert.ToChar(9));
_context.Response.Write(col3 + Convert.ToChar(9) + Environment.NewLine);
}
public bool IsReusable
{
get
{
return false;
}
}
}
