C# 讀取 csv 文中包含逗號(,)的處理
阿新 • • 發佈:2020-12-03
因為csv讀取的方式就是每行按照逗號分隔,如果正文中有逗號,那麼這列欄位就會被引號包裹,這裡給出程式碼,針對這種情況的處理:
1 /// <summary> 2 /// 跳過引號中的逗號,進行逗號分隔(欄位內容中的逗號不參與分隔) 3 /// </summary> 4 /// <param name="strLine"></param> 5 /// <returns></returns> 6 public static string[] CSVstrToArry(stringsplitStr) 7 { 8 var newstr = string.Empty; 9 List<string> sList = new List<string>(); 10 11 bool isSplice = false; 12 string[] array = splitStr.Split(new char[] { ',' }); 13 foreach (var str in array) 14 {15 if (!string.IsNullOrEmpty(str) && str.IndexOf('"') > -1) 16 { 17 var firstchar = str.Substring(0, 1); 18 var lastchar = string.Empty; 19 if (str.Length > 0) 20 { 21 lastchar = str.Substring(str.Length - 1, 1); 22 } 23 if (firstchar.Equals("\"") && !lastchar.Equals("\"")) 24 { 25 isSplice = true; 26 } 27 if (lastchar.Equals("\"")) 28 { 29 if (!isSplice) 30 newstr += str; 31 else 32 newstr = newstr + "," + str; 33 34 isSplice = false; 35 } 36 } 37 else 38 { 39 if (string.IsNullOrEmpty(newstr)) 40 newstr += str; 41 } 42 43 if (isSplice) 44 { 45 //新增因拆分時丟失的逗號 46 if (string.IsNullOrEmpty(newstr)) 47 newstr += str; 48 else 49 newstr = newstr + "," + str; 50 } 51 else 52 { 53 sList.Add(newstr.Replace("\"", "").Trim());//去除字元中的雙引號和首尾空格 54 newstr = string.Empty; 55 } 56 } 57 return sList.ToArray(); 58 }
感謝: