I have written a method that writes a DataTable to a CSV file that looks like this;
public void writeToCSV(DataTable dt)
{
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText("C:\\xampp\\mysql\\data\\sdcdbftest\\test.csv", sb.ToString());
MessageBox.Show("Success");
}
This writes to the CSV file fine, however the issue is when one of our users has inputted a comma in one of the fields that I am building the DataTable from. Excel takes this as a new column, and all of the data ends up in the wrong places when written to Excel.
I have tried using a semicolon instead of a comma but that hasn't worked so far. One way I did get it working is writing to a .txt file with a semicolon as the appended chraracter and then opening it in Excel, of course selecting the semicolon as the delimiter.
Whilst this is a workaround I would rather not make the user do this everytime they open an excel file. Is there a workaround?