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

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.