【问题标题】:How to prevent specific comma delimted values being parsed (C#) [duplicate]如何防止解析特定的逗号分隔值(C#)[重复]
【发布时间】:2011-11-27 20:47:21
【问题描述】:

可能重复:
Dealing with commas in a CSV file

我目前正在解析 CSV 文件中的值并将它们添加到数据表中。

csv 文件包含 5 列,并在将每一行添加到数据表之前对其进行解析。

解析csv后,数据表可视化如下:

|  Town/City  | Cost |
| Birmingham  | 400  |
| Manchester  | 500  |

对于这些数据,没有问题。但是,我有一些如下所示的值:

|  Town/City    | Cost |
|  London, West | 800  |

由于一列的值之间有逗号,因此显然将其解析为单独的列。

数据无法更改,因此我需要一种方法将其解析为单列而不是两列。

到目前为止,这是我的代码,它解析有 5 列的行。我已经评论了我猜新代码需要去的地方。

        //parse csv file and return as data table
    public System.Data.DataTable GetCsvData()
    {
        string strLine;
        char[] charArray = new char[] { ',' };

        List<string> strList = new List<string>();

        System.Data.DataTable dt = new System.Data.DataTable("csvData");
        System.IO.FileStream fileStream = null;
        System.IO.StreamReader streamReader = null;

        if (!string.IsNullOrEmpty(csvFilePath))
        {
            fileStream = new System.IO.FileStream(csvFilePath, System.IO.FileMode.Open);
            streamReader = new System.IO.StreamReader(fileStream);

            strLine = streamReader.ReadLine();

            strList = strLine.Split(charArray).ToList();

            //only add first 5 columns
            for (int i = 0; i <= 4; i++)
                dt.Columns.Add(strList[i].Trim());

            strLine = streamReader.ReadLine();

            while (strLine != null)
            {
                strList = strLine.Split(charArray).ToList();

                System.Data.DataRow dataRow = dt.NewRow();

                /*THIS CODE PARSES THE ROW'S 5 COLUMNS AND NEEDS TO PARSE COMMA
                SEPERATED VALUES AS A SINGLE VALUE*/
                for (int i = 0; i <= 4; i++)
                    dataRow[i] = strList[i].Trim();

                dt.Rows.Add(dataRow);

                strLine = streamReader.ReadLine();
            }

            streamReader.Close();
            return dt;
        }

        return null;
    }

如果我在谷歌上努力寻找答案,我们将不胜感激。

【问题讨论】:

  • 看起来 CSV 无效。包含逗号的字段应使用引号进行转义。
  • 你不能在 csv 中使用另一个分隔符吗?像分号
  • 不能更改数据是个大问题!这就是人们使用不同分隔符或用双引号限定每个值的全部原因。

标签: c# .net excel csv


【解决方案1】:

我建议在拆分后检查数组。如果您发现它有 N + 1 列(您期望 N 的位置),则合并两个 City 列并将其他列向下移动(strList[i] = strList[i+1])。否则正常处理。

当然,这仅适用于您只有一列具有潜在逗号的情况。

【讨论】:

    【解决方案2】:

    除了按照@Bahri 的建议检查拆分数组的长度外,如果您的数据足够可预测(如您的示例中所示),您还可以检查列内容。

    如果您的示例中的成本始终是一个数字,您可以检查它是否只包含数字(或使用正则表达式进行更复杂的匹配)。如果不是,则折叠前两列。

    【讨论】:

      猜你喜欢
      • 2019-03-19
      • 1970-01-01
      • 2017-08-29
      • 2016-06-22
      • 1970-01-01
      • 2010-11-29
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多