文字列をcsv形式から文字列[]またはリストに変換する簡単な方法はありますか?
データにコンマがないことを保証できます。
String.Split はそれをカットするつもりはありませんが、Regex.Split は可能性があります - これを試してください:
using System.Text.RegularExpressions;
string[] line;
line = Regex.Split( input, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
「入力」は csv 行です。これにより、引用符で囲まれた区切り記号が処理され、行の各フィールドを表す文字列の配列が返されます。
堅牢な CSV 処理が必要な場合は、FileHelpersをチェックしてください
試す:
Regex rex = new Regex(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
string[] values = rex.Split( csvLine );
ソース: http://weblogs.asp.net/prieck/archive/2004/01/16/59457.aspx
string[] splitString = origString.Split(',');
(元の回答者によって追加されていない次のコメント) この回答は、データにコンマがないことが保証されている特定のケースに対処していることに注意してください。
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;
}
}
}
}
カンマが埋め込まれた引用符で囲まれた要素を考慮したい場合、特にそれらが引用符で囲まれていないフィールドと混在している場合、これをうまく行う簡単な方法はありません。
また、列名をキーにして、行を辞書に変換することもできます。
これを行うための私のコードは、数百行の長さです。
Web やオープンソース プロジェクトなどにいくつかの例があると思います。
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();
}
引用符で囲まれたフィールドを含む Csv ファイルは、Csv ファイルではありません。名前を付けて保存で「Csv」を選択すると、はるかに多くのもの(Excel)が引用符付きではなく引用符なしで出力されます。
使用、無料、またはコミットできるものが必要な場合は、IDataReader/Record も実行する私のものを次に示します。また、DataTable を使用して、列と DbNull を定義/変換/適用します。
http://github.com/claco/csvdatareader/
それは引用符をしません..まだ。かゆみを掻くために、数日前に一緒に投げました。
忘れたセミコロン: いいリンクです。ありがとう。cfeduke: Microsoft.VisualBasic.FileIO.TextFieldParser へのヒントをありがとう。今夜は CsvDataReader に入ります。
すべての行の string[] を取得します。
string[] lines = System.IO.File.ReadAllLines("yourfile.csv");
次に、それらの行をループして分割します (引用符で区切られたフィールドのコンマをチェックしないため、このエラーが発生しやすくなります)。
foreach (string line in lines)
{
string[] items = line.Split({','}};
}
string test = "one,two,three";
string[] okNow = test.Split(',');
string s = "1,2,3,4,5";
string myStrings[] = s.Split({','}};
Split() は、分割する文字の配列を取ることに注意してください。
separationChar[] = {';'}; // or '\t' ',' etc.
var strArray = strCSV.Split(separationChar);
string[] splitStrings = myCsv.Split(",".ToCharArray());
CsvString.split(',');
一部の CSV ファイルでは、値がコンマとともに二重引用符で囲まれています。したがって、この文字列リテラルで分割できる場合があります: ","