Could somebody please tell me why the following code is not working. The data is saved into the csv file, however the data is not separated. It all exists within the first cell of each row.
StringBuilder sb = new StringBuilder();
foreach (DataColumn col in dt.Columns)
{
sb.Append(col.ColumnName + ',');
}
sb.Remove(sb.Length - 1, 1);
sb.Append(Environment.NewLine);
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
sb.Append(row[i].ToString() + ",");
}
sb.Append(Environment.NewLine);
}
File.WriteAllText("test.csv", sb.ToString());
Thanks.
Here is an enhancement to vc-74's post that handles commas the same way Excel does. Excel puts quotes around data if the data has a comma but doesn't quote if the data doesn't have a comma.
If your calling code is referencing the
System.Windows.Forms
assembly, you may consider a radically different approach. My strategy is to use the functions already provided by the framework to accomplish this in very few lines of code and without having to loop through columns and rows. What the code below does is programmatically create aDataGridView
on the fly and set theDataGridView.DataSource
to theDataTable
. Next, I programmatically select all the cells (including the header) in theDataGridView
and callDataGridView.GetClipboardContent()
, placing the results into the WindowsClipboard
. Then, I 'paste' the contents of the clipboard into a call toFile.WriteAllText()
, making sure to specify the formatting of the 'paste' asTextDataFormat.CommaSeparatedValue
.Here is the code:
Notice I also make sure to preserve the contents of the clipboard before I begin, and restore it once I'm done, so the user does not get a bunch of unexpected garbage next time the user tries to paste. The main caveats to this approach is 1) Your class has to reference
System.Windows.Forms
, which may not be the case in a data abstraction layer, 2) Your assembly will have to be targeted for .NET 4.5 framework, as DataGridView does not exist in 4.0, and 3) The method will fail if the clipboard is being used by another process.Anyways, this approach may not be right for your situation, but it is interesting none the less, and can be another tool in your toolbox.