Commit f453e1aa LN

csv中空格处理

1 个父辈 aa7718be
...@@ -93,6 +93,105 @@ namespace TSA_V.LoadCSVLibrary ...@@ -93,6 +93,105 @@ namespace TSA_V.LoadCSVLibrary
return filePath + bomName + ".csv"; return filePath + bomName + ".csv";
} }
/// <summary> /// <summary>
/// 解析一行CSV数据
/// </summary>
/// <param name="csv">csv数据行</param>
/// <returns></returns>
public static string[] FromCsvLine(string csv)
{
var newstr = string.Empty;
List<string> sList = new List<string>();
bool isSplice = false;
string[] array = csv.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();
}
/// <summary>
/// 反转字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static string Reverse(string str)
{
string revStr = string.Empty;
foreach (char chr in str)
{
revStr = chr.ToString() + revStr;
}
return revStr;
}
/// <summary>
/// 替换CSV中的双引号转义符为正常双引号,并去掉左右双引号
/// </summary>
/// <param name="csvValue">csv格式的数据</param>
/// <returns></returns>
private static string ReplaceQuote(string csvValue)
{
string rtnStr = csvValue;
if (!string.IsNullOrEmpty(csvValue))
{
//首尾都是"
Match m = Regex.Match(csvValue, "^\"(.*?)\"$");
if (m.Success)
{
rtnStr = m.Result("${1}").Replace("\"\"", "\"");
}
else
{
rtnStr = rtnStr.Replace("\"\"", "\"");
}
}
return rtnStr;
}
/// <summary>
/// 添加一个csv文件的数据到位置集合中 /// 添加一个csv文件的数据到位置集合中
/// </summary> /// </summary>
/// <param name="filePath">cvs文件路径+文件名</param> /// <param name="filePath">cvs文件路径+文件名</param>
...@@ -110,12 +209,13 @@ namespace TSA_V.LoadCSVLibrary ...@@ -110,12 +209,13 @@ namespace TSA_V.LoadCSVLibrary
int index = 0; int index = 0;
Dictionary<string, int> propIndexMap = new Dictionary<string, int>(); Dictionary<string, int> propIndexMap = new Dictionary<string, int>();
foreach (var line in lines) foreach (var line in lines)
{ {
var newLine = line.Replace("\"", ""); var newLine = line.Replace("\"", "");
var array = newLine.Split(Spilt_Char); var array = newLine.Split(Spilt_Char);
array = FromCsvLine(line);
if (index == 0) if (index == 0)
{ {
propIndexMap = GetProTitleIndex(newLine, proTitleMap); propIndexMap = GetProTitleIndex(line, proTitleMap);
} }
else else
{ {
......
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!