题
有没有一种简单的方法可以将 csv 格式的字符串转换为 string[] 或列表?
我可以保证数据中没有逗号。
解决方案
string[] splitString = origString.Split(',');
(以下评论不是原回答者添加的) 请记住,这个答案解决了保证数据中没有逗号的特定情况。
其他提示
String.Split 不会削减它,但 Regex.Split 可能 - 尝试这个:
using System.Text.RegularExpressions;
string[] line;
line = Regex.Split( input, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
其中“输入”是 csv 行。这将处理带引号的分隔符,并且应该返回一个表示该行中每个字段的字符串数组。
如果您想要强大的 CSV 处理,请查看 文件助手
尝试:
Regex rex = new Regex(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
string[] values = rex.Split( csvLine );
来源: http://weblogs.asp.net/prieck/archive/2004/01/16/59457.aspx
您可以看看如何使用 Microsoft.VisualBasic 程序集
Microsoft.VisualBasic.FileIO.TextFieldParser
它处理带引号的 CSV(或任何分隔符)。我最近发现它非常方便。
如果您想考虑带有嵌入逗号的引用元素,特别是当它们与非引用字段混合时,没有一种简单的方法可以很好地做到这一点。
您可能还希望将这些行转换为字典,并以列名作为键控。
我执行此操作的代码长达数百行。
我认为网上有一些例子,开源项目等。
尝试这个;
static IEnumerable<string> CsvParse(string input)
{
// null strings return a one-element enumeration containing null.
if (input == null)
{
yield return null;
yield break;
}
// we will 'eat' bits of the string until it's gone.
String remaining = input;
while (remaining.Length > 0)
{
if (remaining.StartsWith("\"")) // deal with quotes
{
remaining = remaining.Substring(1); // pass over the initial quote.
// find the end quote.
int endQuotePosition = remaining.IndexOf("\"");
switch (endQuotePosition)
{
case -1:
// unclosed quote.
throw new ArgumentOutOfRangeException("Unclosed quote");
case 0:
// the empty quote
yield return "";
remaining = remaining.Substring(2);
break;
default:
string quote = remaining.Substring(0, endQuotePosition).Trim();
remaining = remaining.Substring(endQuotePosition + 1);
yield return quote;
break;
}
}
else // deal with commas
{
int nextComma = remaining.IndexOf(",");
switch (nextComma)
{
case -1:
// no more commas -- read to end
yield return remaining.Trim();
yield break;
case 0:
// the empty cell
yield return "";
remaining = remaining.Substring(1);
break;
default:
// get everything until next comma
string cell = remaining.Substring(0, nextComma).Trim();
remaining = remaining.Substring(nextComma + 1);
yield return cell;
break;
}
}
}
}
CsvString.split(',');
获取所有行的 string[]:
string[] lines = System.IO.File.ReadAllLines("yourfile.csv");
然后循环并分割这些行(这很容易出错,因为它不检查引号分隔字段中的逗号):
foreach (string line in lines)
{
string[] items = line.Split({','}};
}
string s = "1,2,3,4,5";
string myStrings[] = s.Split({','}};
请注意,Split() 需要一个 大批 要分割的字符数。
某些 CSV 文件的值带有双引号和逗号。因此有时你可以分割这个字符串文字:“,”
带有引用字段的 Csv 文件不是 Csv 文件。当您在另存为中选择“Csv”时,更多的内容(Excel)不带引号输出,而不是带引号。
如果你想要一个可以使用、免费或承诺的,这里是我的,它也可以做 IDataReader/Record。它还使用 DataTable 来定义/转换/强制列和 DbNull。
http://github.com/claco/csvdatareader/
它不做引号..然而。几天前我只是把它扔在一起来止痒。
忘记分号:很好的链接。谢谢。cfeduke:感谢您对 Microsoft.VisualBasic.FileIO.TextFieldParser 的提示。今晚进入 CsvDataReader。
http://github.com/claco/csvdatareader/ 使用 cfeduke 建议的 TextFieldParser 进行更新。
距离暴露分隔符/修剪空间/类型 ig 仅有一些道具,您只需要代码即可窃取。
我已经在选项卡上进行了拆分,所以这对我来说很有效:
public static string CsvToTabDelimited(string line) {
var ret = new StringBuilder(line.Length);
bool inQuotes = false;
for (int idx = 0; idx < line.Length; idx++) {
if (line[idx] == '"') {
inQuotes = !inQuotes;
} else {
if (line[idx] == ',') {
ret.Append(inQuotes ? ',' : '\t');
} else {
ret.Append(line[idx]);
}
}
}
return ret.ToString();
}
string test = "one,two,three";
string[] okNow = test.Split(',');
separationChar[] = {';'}; // or '\t' ',' etc.
var strArray = strCSV.Split(separationChar);
string[] splitStrings = myCsv.Split(",".ToCharArray());