Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting DataSet/DataTable to CSV

Tags:

c#

.net

ado.net

Please let me know, if there any way to generate CSV files from a DataTable or DataSet? To be specific, without manually iterating through rows of DataTable and concatenating.

Please help

like image 469
AbrahamJP Avatar asked Feb 03 '11 09:02

AbrahamJP


People also ask

How do I save Comma Separated Values in CSV?

To save an Excel file as a comma-delimited file: From the menu bar, File → Save As. Next to “Format:”, click the drop-down menu and select “Comma Separated Values (CSV)” Click “Save”

How do I return a CSV file in C#?

Using new streamwriter to return CSV files The CSV headers (the names of the object properties, e.g. FirstName, LastName) are written on the first line. The object is then looped through and each property's value on the object are written, comma delimited.


2 Answers

There are several ways to do that.

One of the simplest (IMO) is using FileHelpers Library

FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);
like image 124
digEmAll Avatar answered Oct 03 '22 23:10

digEmAll


A relative simple, compact and quite flexible solution could be the following extension method:

public static string ToCsv(this DataTable table, string colSep = "", string rowSep = "\r\n")
{
    var format = string.Join(colSep, Enumerable.Range(0, table.Columns.Count)
                                            .Select(i => string.Format("{{{0}}}", i)));

    return string.Join(rowSep, table.Rows.OfType<DataRow>()
                                        .Select(i => string.Format(format, i.ItemArray)));
}

Please note that this solution could cause problems with huge amounts of data, in which case you should stream the output. Quoting and formatting would of course make the code more complex.

like image 43
Alexander Stojakovic Avatar answered Oct 03 '22 23:10

Alexander Stojakovic