asp.net CSV 文字列を string[] に変換します
質問
文字列を CSV 形式から string[] またはリストに変換する簡単な方法はありますか?
データにカンマが含まれていないことを保証できます。
解決
string[] splitString = origString.Split(',');
(以下のコメントは元の回答者が追加したものではありません) この回答は、データ内にカンマが含まれていないことが保証される特定のケースに対処していることに注意してください。
他のヒント
String.Split だけではうまくいきませんが、Regex.Split なら可能性があります。これを試してみてください。
using System.Text.RegularExpressions;
string[] line;
line = Regex.Split( input, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
ここで、「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 (または任意の区切り文字) を処理します。最近とても便利だと感じています。
カンマが埋め込まれた引用符で囲まれた要素を考慮したい場合、特に引用符で囲まれていないフィールドが混在している場合、これをうまく行う簡単な方法はありません。
また、列名をキーとした行を辞書に変換することもできます。
これを行うためのコードは数百行になります。
Web やオープンソース プロジェクトなどにいくつかの例があると思います。
これを試して;
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());