我正在尝试导出到 CSV,但是我面临的问题是网格视图中包含的数据包含逗号。由于使用“,”作为分隔符,这会导致 csv 中出现各种问题。下面是代码。有什么想法可以避免这种情况吗?
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);
}
}
}