7

文字列をcsv形式から文字列[]またはリストに変換する簡単な方法はありますか?

データにコンマがないことを保証できます。

4

17 に答える 17

17

String.Split はそれをカットするつもりはありませんが、Regex.Split は可能性があります - これを試してください:

using System.Text.RegularExpressions;

string[] line;
line = Regex.Split( input, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

「入力」は csv 行です。これにより、引用符で囲まれた区切り記号が処理され、行の各フィールドを表す文字列の配列が返されます。

于 2008-09-16T15:33:32.710 に答える
8

堅牢な CSV 処理が必要な場合は、FileHelpersをチェックしてください

于 2008-09-16T15:17:49.190 に答える
2

試す:

Regex rex = new Regex(",(?=([^\"]*\"[^\"]*\")*(?![^\"]*\"))");
string[] values = rex.Split( csvLine );

ソース: http://weblogs.asp.net/prieck/archive/2004/01/16/59457.aspx

于 2008-09-16T15:24:07.663 に答える
2
string[] splitString = origString.Split(',');

(元の回答者によって追加されていない次のコメント) この回答は、データにコンマがないことが保証されている特定のケースに対処していることに注意してください。

于 2008-09-16T15:11:19.957 に答える
2

Microsoft.VisualBasic アセンブリを

Microsoft.VisualBasic.FileIO.TextFieldParser

引用符付きの CSV (または任意の区切り記号) を処理します。最近とても便利だと思います。

于 2008-09-16T16:04:59.220 に答える
1

これを試して;

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;
            }
        }
    }

}
于 2008-09-16T16:13:10.697 に答える
1

カンマが埋め込まれた引用符で囲まれた要素を考慮したい場合、特にそれらが引用符で囲まれていないフィールドと混在している場合、これをうまく行う簡単な方法はありません。

また、列名をキーにして、行を辞書に変換することもできます。

これを行うための私のコードは、数百行の長さです。

Web やオープンソース プロジェクトなどにいくつかの例があると思います。

于 2008-09-16T15:18:19.877 に答える
0

http://github.com/claco/csvdatareader/cfedukeによって提案されたTextFieldParserを使用して更新されました。

セパレーター/トリムスペース/タイプigを公開することからほんの少し離れたところに、盗むためのコードが必要です。

于 2008-09-17T04:33:19.997 に答える
0

私はすでにタブで分割していたので、これは私のためのトリックをしました:

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();
}
于 2008-09-17T15:40:22.450 に答える
0

引用符で囲まれたフィールドを含む Csv ファイルは、Csv ファイルではありません。名前を付けて保存で「Csv」を選択すると、はるかに多くのもの(Excel)が引用符付きではなく引用符なしで出力されます。

使用、無料、またはコミットできるものが必要な場合は、IDataReader/Record も実行する私のものを次に示します。また、DataTable を使用して、列と DbNull を定義/変換/適用します。

http://github.com/claco/csvdatareader/

それは引用符をしません..まだ。かゆみを掻くために、数日前に一緒に投げました。

忘れたセミコロン: いいリンクです。ありがとう。cfeduke: Microsoft.VisualBasic.FileIO.TextFieldParser へのヒントをありがとう。今夜は CsvDataReader に入ります。

于 2008-09-16T15:30:48.427 に答える
0

すべての行の string[] を取得します。

string[] lines = System.IO.File.ReadAllLines("yourfile.csv");

次に、それらの行をループして分割します (引用符で区切られたフィールドのコンマをチェックしないため、このエラーが発生しやすくなります)。

foreach (string line in lines)
{
    string[] items = line.Split({','}};
}
于 2008-09-16T15:12:33.370 に答える
0
string test = "one,two,three";
string[] okNow = test.Split(',');
于 2008-09-16T15:13:33.587 に答える
0
string s = "1,2,3,4,5";

string myStrings[] = s.Split({','}};

Split() は、分割する文字の配列を取ることに注意してください。

于 2008-09-16T15:13:40.510 に答える
0
separationChar[] = {';'}; // or '\t' ',' etc.
var strArray = strCSV.Split(separationChar);
于 2008-09-16T15:13:49.670 に答える
0
string[] splitStrings = myCsv.Split(",".ToCharArray());
于 2008-09-16T15:15:19.180 に答える
0
CsvString.split(',');
于 2008-09-16T15:10:58.070 に答える
0

一部の CSV ファイルでは、値がコンマとともに二重引用符で囲まれています。したがって、この文字列リテラルで分割できる場合があります: ","

于 2008-09-16T15:26:39.013 に答える