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();
}