ASP.NET: Downloading a DataTable in CSV Format

Here's a really quick tip: how to convert a DataTable to CSV, and write it dynamically to the response stream.

In ASP.NET, If you need to allow users to download the contents of a datatable in flat file format (i.e. CSV, TAB etc) you could do this by writing the data to a temporary file, then writing the resulting file to the response using TransmitFile. However, a quicker and less expensive method is to stream it directly. Here's a method which allows you to do just that:

///

/// Writes a datatable in delimited file format to the response stream. /// /// /// /// private void WriteDelimitedData(DataTable dt, string fileName, string delimiter) { //prepare the output stream Response.Clear; Response.ContentType = "text/csv"; Response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));

//write the csv column headers for (int i = 0; i < dt.Columns.Count; i++) { Response.Write(dt.Columns[i].ColumnName); Response.Write((i < dt.Columns.Count - 1)? delimiter: Environment.NewLine); }

//write the data foreach (DataRow row in dt.Rows) { for (int i = 0; i < dt.Columns.Count; i++) { Response.Write(row[i].ToString); Response.Write((i < dt.Columns.Count - 1)? delimiter: Environment.NewLine); } }

Response.End; }

And here's an example of calling the above method with some test data:

//create a datatable to hold the test data DataTable dt = new DataTable; dt.Columns.Add("Column 1", typeof(string)); dt.Columns.Add("Column 2", typeof(string));

//generate some random data in the datatable Random rnd = new Random; for (int i = 0; i < 100; i++) { dt.Rows.Add(rnd.Next(1, 1000000).ToString, rnd.Next(1, 1000000).ToString); }

this.WriteDelimitedData(dt, "testdata.csv", ",");

Quick, and easy!

This article is part of the GWB Archives. Original Author: Adam Pooler

New on Geeks with Blogs