【C#】讀取CSV文中包含逗號(,)的例外處理
CSV Sample內容:
"F0406891","2017/01","E-0221","260041","wo","1.20000004768372" "F0406892","2017/02","E-0221","260041","wo,ac","2.30000004768356"
部分程式碼(Sample):
//先用\n把資料分行
string[] CSVSec=CSV.Split('\n');
string[] CSVSec=CSV.Split('\n');
.... 省略之 ...
//逐行抓出結果,並切割後排除事廢排除項目
for(int i=0;i<CSVSec.Length;i++)
{
//先判斷雙引號(")中的字串是否含有逗號(,),需做特別處理
string[] CSVItem = CSVstrToArry(CSVSec[i]);
string[] CSVItem = CSVstrToArry(CSVSec[i]);
.... 省略之 ...
}
函式:
#region 先判斷雙引號(")中的字串是否含有逗號(,),需做特別處理
/// <summary>
/// 跳過引號中的逗號,進行逗號分隔(字段內容中的逗號不加入分隔)
/// </summary>
/// <param name="strLine"></param>
/// <returns></returns>
public static string[] CSVstrToArry(string splitStr)
{
var newstr = string.Empty;
List<string> sList = new List<string>();
bool isSplice = false;
string[] array = splitStr.Split(new char[] { ',' });
foreach (var str in array)
{
if (!string.IsNullOrEmpty(str) && str.IndexOf('"') > -1)
{
var firstchar = str.Substring(0, 1);
var lastchar = string.Empty;
if (str.Length > 0)
{
lastchar = str.Substring(str.Length - 1, 1);
}
if (firstchar.Equals("\"") && !lastchar.Equals("\""))
{
isSplice = true;
}
if (lastchar.Equals("\""))
{
if (!isSplice)
newstr += str;
else
newstr = newstr + "," + str;
isSplice = false;
}
}
else
{
if (string.IsNullOrEmpty(newstr))
newstr += str;
}
if (isSplice)
{
//加入因拆分時遺失的逗號
if (string.IsNullOrEmpty(newstr))
newstr += str;
else
newstr = newstr + "," + str;
}
else
{
sList.Add(newstr.Replace("\"", "").Trim());//去除字符中的雙引號和首尾空格
newstr = string.Empty;
}
}
return sList.ToArray();
}
#endregion
/// <summary>
/// 跳過引號中的逗號,進行逗號分隔(字段內容中的逗號不加入分隔)
/// </summary>
/// <param name="strLine"></param>
/// <returns></returns>
public static string[] CSVstrToArry(string splitStr)
{
var newstr = string.Empty;
List<string> sList = new List<string>();
bool isSplice = false;
string[] array = splitStr.Split(new char[] { ',' });
foreach (var str in array)
{
if (!string.IsNullOrEmpty(str) && str.IndexOf('"') > -1)
{
var firstchar = str.Substring(0, 1);
var lastchar = string.Empty;
if (str.Length > 0)
{
lastchar = str.Substring(str.Length - 1, 1);
}
if (firstchar.Equals("\"") && !lastchar.Equals("\""))
{
isSplice = true;
}
if (lastchar.Equals("\""))
{
if (!isSplice)
newstr += str;
else
newstr = newstr + "," + str;
isSplice = false;
}
}
else
{
if (string.IsNullOrEmpty(newstr))
newstr += str;
}
if (isSplice)
{
//加入因拆分時遺失的逗號
if (string.IsNullOrEmpty(newstr))
newstr += str;
else
newstr = newstr + "," + str;
}
else
{
sList.Add(newstr.Replace("\"", "").Trim());//去除字符中的雙引號和首尾空格
newstr = string.Empty;
}
}
return sList.ToArray();
}
#endregion
程式部分節錄Sample截圖參考:

留言
張貼留言