一个简单的 CSV 读取器






4.94/5 (3投票s)
一种简单的方法来读取 CSV 文件。
介绍
本技巧详细介绍了一种读取 CSV 文件的简单方法。
使用代码
读取 CSV 文件时,主要问题在于确定逗号是用于分隔值,还是值的一部分。以下代码片段解决了这个问题
if (c == ‘,’ && quoteCount % 2 == 0)
{
//comma is being used as a separator
}
其中变量 c
是当前正在考虑的字符,quoteCount
是当前 string
中 ‘”’
字符的累计总数。使用这种方法,可以编写一个简单(虽然不一定健壮)的 CSV 读取器,只需几行代码。
public static List<List<string>> ReadCsv(string[] data, char separator)
{
var rows = new List<List<string>>();
foreach (string text in data)
{
int quoteCount = 0;
int startIndex = 0;
int endIndex = 0;
var cols = new List<string>();
foreach (char c in text)
{
if (c == '"')
{
quoteCount += 1;
}
else
{
if (c == separator && quoteCount % 2 == 0)
{
cols.Add(trimQuotes(text.Substring(startIndex, endIndex - startIndex)));
startIndex = endIndex + 1;
}
}
endIndex++;
}
cols.Add(trimQuotes(text.Substring(startIndex, endIndex - startIndex)));
rows.Add(cols);
}
return rows;
}
private static string trimQuotes(string text)
{
if (String.IsNullOrEmpty(text))
{
return text;
}
return text[0] == '"' && text.Length > 2
? text.Substring(1, text.Length - 2).Replace("\"\"", "\"")
: text.Replace("\"\"", "\"");
}
结论
我感谢 Jonathan Wood 的优秀文章,在 C# 中读取和写入 CSV 文件,它是我撰写本技巧的灵感来源。他将文本解析为 CSV 格式的方法非常出色。