You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.0 KiB

using System;
using System.Collections.Generic;
using System.Text;
namespace Apewer.Internals
{
internal class CsvHelper
{
/// <summary>读取 .CSV 文件。</summary>
public static List<List<string>> ReadCSV(string argText)
{
var result = new List<List<string>>();
if (string.IsNullOrEmpty(argText)) return result;
var rows = argText.Split('\n');
var vramarray = new List<string[]>();
foreach (var row in rows)
{
var list = ResolveCSV(row);
if (list.Count > 0) result.Add(list);
}
return result;
}
/// <summary>解析 .CSV 文件。</summary>
private static List<string> ResolveCSV(string argRowText)
{
if (string.IsNullOrEmpty(argRowText)) return new List<string>();
var trim = argRowText.Trim();
if (string.IsNullOrEmpty(trim)) return new List<string>();
var list = new List<string>();
var quote = false;
var cell = "";
for (int i = 0; i < argRowText.Length; i++)
{
var vchar = argRowText[i];
switch (vchar)
{
case '"':
if (!quote) cell = "";
quote = !quote;
break;
case ',':
if (quote)
{
cell += vchar;
}
else
{
list.Add(cell.Trim());
cell = "";
}
break;
default:
cell += vchar;
break;
}
}
if (!string.IsNullOrEmpty(cell))
{
list.Add(cell.Trim());
cell = "";
}
return list;
}
}
}