首页 / 知识

关于c#:asp.net将CSV字符串转换为字符串[]

2023-04-15 23:54:00

关于c#:asp.net将CSV字符串转换为字符串[]

asp.net Convert CSV string to string[]

有没有简单的方法可以将字符串从csv格式转换为字符串[]或列表?

我可以保证数据中没有逗号。


String.Split只是不打算剪切它,但是Regex.Split可以-尝试以下方法:

1
2
3
4
using System.Text.RegularExpressions;

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

其中"输入"是csv行。这将处理用引号引起来的定界符,并应给您返回代表该行中每个字段的字符串数组。


如果您需要强大的CSV处理功能,请查看FileHelpers


1
string[] splitString = origString.Split(',');

(以下评论未由原始回答者添加)
请记住,此答案是针对特定情况的,在这种情况下,保证数据中没有逗号。


尝试:

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

资料来源:http://weblogs.asp.net/prieck/archive/2004/01/16/59457.aspx


您可以看看将Microsoft.VisualBasic程序集与

1
Microsoft.VisualBasic.FileIO.TextFieldParser

它处理带引号的CSV(或任何定界符)。我最近发现它非常方便。


尝试这个;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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;
            }
        }
    }

}


如果要考虑带有嵌入式逗号的带引号的元素,尤其是如果它们与非带引号的字段混合使用,则没有简单的方法可以很好地做到这一点。

您可能还希望将这些行转换为字典,并以列名作为关键字。

我执行此操作的代码长数百行。

我认为网络上有一些示例,开源项目等等。


带有引号字段的Csv文件不是Csv文件。在另存为中选择" Csv"时,更多的东西(Excel)输出没有引号,而不是带有引号。

如果您想要一个可以使用,免费或致力于的工具,那么这里也是IDataReader / Record的工具。它还使用DataTable定义/转换/强制列和DbNull。

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

它不做引号..呢。我只是几天前把它扔在一起挠痒痒。

被遗忘的分号:不错的链接。谢谢。
cfeduke:感谢您对Microsoft.VisualBasic.FileIO.TextFieldParser的提示。今晚进入CsvDataReader。


某些CSV文件在值的双引号和逗号之间。因此,有时您可以拆分此字符串文字:","


我已经在选项卡上分开了,所以这对我有用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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();
}

1
CsvString.split(',');


1
string[] splitStrings = myCsv.Split(",".ToCharArray());

1
2
separationChar[] = {';'}; // or '\t' ',' etc.
var strArray = strCSV.Split(separationChar);

1
2
3
string s ="1,2,3,4,5";

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

请注意,Split()需要一个字符数组进行分割。


1
2
string test ="one,two,three";
string[] okNow = test.Split(',');

获取所有行的字符串[]:

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

然后循环遍历并拆分这些行(容易出错,因为它不检查引号分隔字段中的逗号):

1
2
3
4
foreach (string line in lines)
{
    string[] items = line.Split({','}};
}


http://github.com/claco/csvdatareader/使用cfeduke建议的TextFieldParser更新。

只需暴露一些分隔符/ trimspaces / type ig即可,您仅需要一些代码即可窃取。


字符串方法列表数据

最新内容

相关内容

猜你喜欢