Generating a CSV File from ASP.Net

A really handy feature for web-based data tools is ability to let your users download their data in a CSV format so they can edit it in Excel or their favorite spread sheet program. Fortunately this is also really simple to code:

CSV Files

Typically a set of comma delimited values (e.g. CSV) with a linefeed between rows. Check here for CSV File Format Spec.

Generating your file

You have a couple options to build the file, the first is to build it manually by concatenating a bunch of strings and commas together. If you are going this route, be sure to use a System.Text.StringBuilder class to increase performance over the normal String class.

The second option is that you could auto generate the file if you already have an ASP.Net data object handy, like a DataSet or DataGrid. Just use the DataGrid.RenderControl() method:

DataSet dataset = newDataSet();

// Fill your data set with actual data

DataGrid datagrid = new DataGrid();
datagrid.DataSource = dataset.Tables[0];
datagrid.DataBind();

StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
datagrid.RenderControl(htmlWriter);
String myFile = stringWriter.ToString();

Writing the data to the buffer:

String myFile = "First Name, Last Name, Telephone\nJon, Smith, 555-555-5555\nBill, Thomas, 555-555-5555\n";
String myFileName = "Addressbook.csv";

Response.ContentType = "text/comma-separated-values";
Response.AddHeader("content-disposition", "attachment; filename=" + myFileName);
Response.Buffer = true;
Response.Write(myFile);
Response.End();

And it is as simple as that.

Posted on December 3, 2006

Add comment


 

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

July 23. 2008