Export a DataTable to Excel in ASP.NET

Oct 22, 2006

Back in February I wrote a post on how to export DataTables to XML and Excel and I still get a lot of search engine traffic to that post. People have been asking me to simplify the example and only concentrate on the Excel export, so that’s what I will do now.

All spreadsheet applications (Excel, Calc etc.) understand semicolon separated files natively, so everyone can use this method – you don’t even have to use Excel for it to work.

public static void ExportToSpreadsheet(DataTable table, string name)

{

  HttpContext context = HttpContext.Current;

  context.Response.Clear();

 

  foreach (DataColumn column in table.Columns)

  {

    context.Response.Write(column.ColumnName + ";");

  }

 

  context.Response.Write(Environment.NewLine);

 

  foreach (DataRow row in table.Rows)

  {

    for (int i = 0; i < table.Columns.Count; i++)

    {

      context.Response.Write(row[i].ToString().Replace(";", string.Empty) + ";");

    }

    context.Response.Write(Environment.NewLine);

  }

 

  context.Response.ContentType = "text/csv";

  context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");

  context.Response.End();

}

>

Then just call this method and pass the DataTable and the filename as parameters.

ExportToSpreadsheet(table, "products");

The method is static so you can use it anywhere in a web application. Put it on a page, a HTTP Handler, add it to the App_Code folder or stick it in a separate assembly. As long as you call it from a web application it will work.

* $4.95/month BlogEngine.net Hosting – Click Here!

Comments (4) -

 Tomas Restrepo
Tomas Restrepo
10/22/2006 1:57:29 PM #

One thing to watch out for when generating CSV files is that the field separator is not necessarily a ',' or a ';'. How excel interprets the file willl depend on the local regional settings the user has configured, so exporting CSV files is in general fairly problematic. For this reasin I've always preferred to export Tab-delimited files (TSV), which don't have that problem.

Another thing to watch out for and that you might not be taking into account in your sample is embedded delimiters in field values, in which case you need to wrap it in double quotes to ensure excel can read it.

Mads Kristensen
Mads Kristensen
10/22/2006 3:25:40 PM #

Tomas, that's a good point. I wasn't aware of that. I've never had problems with using a ';' as the delimiter on both en-US, en-GB and da-DK systems. The tab delimiter however, I can't make work on any of them.

Morten Krog
Morten Krog
10/22/2006 8:07:12 PM #

Doesn't work on excel on a mac. I came up with a solution very similar to this a few months ago only to end up in an enourmous struggel getting it to work on a mac.

In the end I had to implement a svk format rather than csv. That worked cross platform.

Robert M Bishop
Robert M Bishop United States
2/24/2009 5:43:13 PM #

Why does this not work for me?

I get this error.

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed.  Common causes for this error are then the reponse. is modified by calls to Repsonse.Write(), response fiters, httpModules, or server trace is enabled.  Details: Error parsing near 'ID;Number;ProducSer'.

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.