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
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”
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.
There are several ways to do that.
One of the simplest (IMO) is using FileHelpers Library
FileHelpers.CsvEngine.DataTableToCsv(dataTable, filename);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With