数据包含逗号时从Gridview导出为CSV

时间:2012-10-22 14:03:48

标签: c# csv datagridview

我正在尝试导出为CSV,但是我遇到的问题是网格视图中包含的数据包含逗号。由于a“,”用作分隔符,因此会导致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);
                    }
                }
            }

2 个答案:

答案 0 :(得分:0)

您可以使用任何库导出为CSV。

答案 1 :(得分:0)

使用转义字符,并使用了解如何处理转义的解析器。您可以快速编写Escape()扩展名和Unescape()扩展名....

public static class ExtentionClass
{
    public static string Escape(this string str)
    {
          return str.Replace("\\","\\\\").Replace(",","\\,");
    }
    public static string Unescape(this string str)
    {
          return str.Replace("\\\\","\\").Replace("\\,",",");
    }
}

现在你可以将你的行改为......

dataFromGrid = dataFromGrid + ',' + dataRowObject.Cells[i].Value.ToString().Escape();

但是,您可能想要在Excel中查看输出,然后\不起作用......需要双引号。

...
    public static string Escape(this string str)
    {
        return "\"" + str.Replace("\"","\"\"") + "\"";
    }

您可以在...阅读更多内容 CSV for Excel, Including Both Leading Zeros and Commas