Runtime Debugger

kannan M ambadi

Exporting Dataset as CSV

Hi Everyone,

Below given an easy way to export data from a dataset as CSV(comma seperated values) . At first, it converts the datatable to html table format and then writes data as output stream. We need to set the Content-Type of Response object as Excel format and add the filename to be streamed on the client browser in a dialog box

Check this snippet

private void ExportToCsvFromDataSet(DataSet dsExport) {

bool IsOutputStreamed = false;

try {

StringBuilder dataToExport = new StringBuilder();

foreach (DataTable dtExport in dsExport.Tables) {

string headerToExport= string.Empty;

foreach (DataColumn dCol in dtExport.Columns)

headerToExport = (char)34 + dCol.ColumnName + (char)34 + (char)44;

headerToExport.Remove(headerToExport.Length - 1, 1);

headerToExport = headerToExport + Environment.NewLine + Environment.NewLine;

dataToExport.Append(headerToExport);

string bodyToExport = string.Empty;

foreach (DataRow dRow in dtExport.Rows) {

foreach (object obj in dRow.ItemArray)

bodyToExport = bodyToExport + obj.ToString() + (char)44;

bodyToExport.Remove(bodyToExport.Length - 1, 1);

bodyToExport = bodyToExport + Environment.NewLine;

}

dataToExport.Append(bodyToExport);

dataToExport.Append(Environment.NewLine);

dataToExport.Append(Environment.NewLine);

if (string.IsNullOrEmpty(dataToExport.ToString())) {

Response.Clear();

Response.ContentType = "Text/vnd.ms-excel";

Response.AddHeader("Content-Disposition", "attachment;filename=report.csv");

Response.Write(dataToExport.ToString());

IsOutputStreamed = true;

}

}

}

catch { }

finally {

if (IsOutputStreamed)

Response.End();

}

}

Download the source code

Comments

samreen said:

i like it n want to use it

# November 20, 2008 6:10 AM

Steve said:

Here's an alternative that returns the CSV as a string:

public static string ConvertDataSetToCSV(DataSet ds)

{

const string LC_COMMA = ",";

const string LC_DBLQUOTE = "\"";

const string LC_DBLQUOTE_ESC = "\"\"";

StringBuilder csv = new StringBuilder();

foreach (DataTable tbl in ds.Tables)

{

// Append the table's column headers.

foreach (DataColumn col in tbl.Columns)

{

csv.Append(LC_DBLQUOTE + col.ColumnName + LC_DBLQUOTE + LC_COMMA);

}

csv.Length -= 1;

csv.Append(Environment.NewLine);

// Append the table's data.

foreach (DataRow row in tbl.Rows)

{

foreach (object val in row.ItemArray)

{

csv.Append(LC_DBLQUOTE + val.ToString().Replace(LC_DBLQUOTE, LC_DBLQUOTE_ESC)

+ LC_DBLQUOTE + LC_COMMA);

}

csv.Length -= 1;

csv.Append(Environment.NewLine);

}

// Add an empty line between this and the next table.

csv.Append(Environment.NewLine);

}

return csv.ToString();

}

# October 1, 2009 8:31 AM

kikus said:

тема не раскрыта.. может есть ещё информация по этому поводу?

# June 13, 2010 7:48 PM

andes said:

nice.  this works well.  I'd call replace on the cell strings to make sure no extra commas get into the csv:

foreach (object curRow in tempArray)

{                                bodyToExport.Append(curRow.ToString().Replace(",", " "));                            bodyToExport.Append((char)44);

}

# June 17, 2010 2:21 PM

suneel said:

Hi,

A very gud article. I did the same in my web apllication to export a dataset to a CSV file.

I'm getting an exception if the number of rows in the dataset exceeds 10000. Can you please help me out?

Thanks,

Suneel k R

suneelcse@gmail.com

# November 10, 2010 2:09 AM

Pupeevetlylit said:

Доброго времени суток,  

Хочу представить вам прозелит магазин курительных смесей

сайт магазина http://spice-family.ru  

3г микса Moderate - 1,500 р. + доставка (ems, pony get across)  

Сообразно вопросам опта вносить вразброд в скайп - FomaX2

# September 3, 2011 1:13 AM

KateFrakloop said:

Cool article to my mind. Keep it up!

Kate Frakloop

<a href="cyprusescorts.us/">Limassol escorts</a>

# November 5, 2011 7:39 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)