I am trying to export to CSV, however the problem I am facing is when the data contained within the grid view contains comma’s. Since the a “,”, is used as the delimiter this is causing all sorts of issues within the csv. Below is the code. Any ideas how I can avoid this?
try
{
System.IO.StreamWriter csvFileWriter = new StreamWriter(CsvFpath, false);
string columnHeaderText = "";
int countColumn = dataGridViewLogging.ColumnCount - 1;
if (countColumn >= 0)
{
columnHeaderText = dataGridViewLogging.Columns[0].HeaderText;
}
for (int i = 1; i <= countColumn; i++)
{
columnHeaderText = columnHeaderText + ',' + dataGridViewLogging.Columns[i].HeaderText;
}
csvFileWriter.WriteLine(columnHeaderText);
foreach (DataGridViewRow dataRowObject in dataGridViewLogging.Rows)
{
if (!dataRowObject.IsNewRow)
{
string dataFromGrid = "";
dataFromGrid = dataRowObject.Cells[0].Value.ToString();
for (int i = 1; i <= countColumn; i++)
{
dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString();
csvFileWriter.WriteLine(dataFromGrid);
}
}
}
Use an escape character, and use a parser that understands how to deal with escapes. You can quickly write an Escape() extension and an Unescape() extension….
now you can change your line to…
But, you are probably wanting to view the output in Excel, then \ doesn’t work… It needs to be double quoted.
You can read more at…
CSV for Excel, Including Both Leading Zeros and Commas