Geeks With Blogs
The Quandary Phase This code was generated by a tool.

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:

        /// <summary>
        /// Writes a datatable in delimited file format to the response stream.
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="fileName"></param>
        /// <param name="delimiter"></param>
        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 Open-mouthed Posted on Thursday, January 29, 2009 12:09 PM | Back to top


Comments on this post: ASP.NET: Downloading a DataTable in CSV Format

# re: ASP.NET: Downloading a DataTable in CSV Format
Requesting Gravatar...
Thanks for the great code.
Left by Wealthy Affiliate on Nov 13, 2009 9:33 AM

# re: ASP.NET: Downloading a DataTable in CSV Format
Requesting Gravatar...
Good looking code but will this increase your site traffic/utilization stats? I guess not, the file is the same size regardless of delivery.
Left by Charles on Jan 18, 2010 3:15 AM

# re: ASP.NET: Downloading a DataTable in CSV Format
Requesting Gravatar...
@Charles: No, not as it stands. However, you can look into compressing your HTTP responses, and this will decrease the amount of data you need to send. Have a look at this article for more info:

http://www.west-wind.com/Weblog/posts/10564.aspx
Left by adampooler on Jan 18, 2010 3:52 AM

# re: ASP.NET: Downloading a DataTable in CSV Format
Requesting Gravatar...
Great little method, just put it into play today.

My small modification:

if (row[i].ToString().IndexOf(",") > -1)
{
Response.Write("\"" + row[i].ToString() + "\"");
}
else
{
Response.Write(row[i].ToString());
}

Which handles if there is a comma in the data of a given column.

Thanks for sharing!
Left by Mike Duncan on Mar 11, 2010 8:30 AM

# re: ASP.NET: Downloading a DataTable in CSV Format
Requesting Gravatar...
great code... thanks...
Left by Anurag on Sep 09, 2010 8:09 AM

# classic ugg boots
Requesting Gravatar...
a comma in the data of a given column.Ugg Cardy Boots
Bailey Button Ugg Boots
Left by ugg on Oct 31, 2010 3:27 PM

# re: ASP.NET: Downloading a DataTable in CSV Format
Requesting Gravatar...
great info for me ,thanks
Left by ugg fluff flip flop on Nov 17, 2010 6:31 PM

# re: ASP.NET: Downloading a DataTable in CSV Format
Requesting Gravatar...
I really enjoyed the article. It proved to be very useful to me and I am sure to all the commentators here!
Left by Indonesian Teak Garden Furniture on Dec 07, 2010 5:17 AM

# re: ASP.NET: Downloading a DataTable in CSV Format
Requesting Gravatar...
A while back immediately after MIX 10 I started messing with Microsoft Translator APIs Silverights applications. I also got some people asking about Windows Phone 7 stuff and messed around with that bit.Here's some for referance......!!
Left by High pagerank backlinks on Mar 02, 2011 12:38 AM

Comments have been closed on this topic.
Copyright © Adam Pooler | Powered by: GeeksWithBlogs.net | Join free