【问题标题】:Export to CSV from Gridview when data contains commas当数据包含逗号时从 Gridview 导出为 CSV
【发布时间】:2012-10-22 14:03:47
【问题描述】:

我正在尝试导出为 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);
                    }
                }
            }

【问题讨论】:

  • 将分隔符更改为;并在csv文件中首先设置sep=;即可。
  • 将字段用双引号括起来,可以包含逗号并使用available csv parser 而不是手动进行。
  • 您能不能简单地使用不同的不太常见的字符作为分隔符,例如|,或者将违规文本包装在"" 中,这样大多数应用程序都应该可以解析。跨度>
  • 用双引号将你的数据项封装起来不能解决你的问题吗?即“数据项 1”、“数据项 2”、“数据项 3”等。
  • 这个 CSV 文件的目标消费者是什么?

标签: c# csv datagridview


【解决方案1】:

使用转义字符,并使用了解如何处理转义的解析器。你可以快速编写一个 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 2021-01-24
      • 2018-01-10
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多