对包含逗号、引号的CSV字符串的解析函数

xiaoxiao2021-02-28  50

csv文件一般格式为:

A,B,C

1,2,3

4,5,6

但是当文件内存储有逗号、引号,如果只是用split(",")会导致在存在逗号的情况下出错。

如:

A,B,C

1,“2,2",3

4,"""5",6

以下函数输入:

            string ll = @"4,""""""5"",6,""2,3""";//从excel中查看的数据显示 4|"5|6|2,3,保存的字符串为4,"""5",6,"2,3"             string[] a = CSVstrToAry(ll);

 输出:

           a[0]:4

           a[1]:”5

           a[2]:6

           a[3]:2,3

函数如下:

private static string[] CSVstrToAry(string strLine) { string strItem = string.Empty; int semicolonFlg = 0;//单数时肯定不是某一列的结束位置 List<string> lstStr = new List<string>(); string strA = string.Empty; for (int i = 0; i < strLine.Length; i++) { strA = strLine.Substring(i, 1); if (strA == "\"") semicolonFlg += 1; if (semicolonFlg == 2) semicolonFlg = 0; if (strA == "," && semicolonFlg == 0) { if (strItem.Contains("\"")) { strItem = strItem.Replace("\"\"", @"""");//CSV中引号也会有转义,单引号会转换为双引号 if (strItem.StartsWith("\"") && strItem.EndsWith("\"")) { strItem = strItem.Substring(1, strItem.Length - 2); } } lstStr.Add(strItem); strItem = string.Empty; } else { strItem += strA; } } if (strItem.Length > 0) { if (strItem.Contains("\"")) { strItem = strItem.Replace("\"\"", @"""");//CSV中引号也会有转义,单引号会转换为双引号 if (strItem.StartsWith("\"") && strItem.EndsWith("\"")) { strItem = strItem.Substring(1, strItem.Length - 2); } } lstStr.Add(strItem); } return lstStr.ToArray(); }

转载请注明原文地址: https://www.6miu.com/read-65867.html

最新回复(0)