【问题标题】:asp.net Convert CSV string to string[]asp.net 将 CSV 字符串转换为字符串 []
【发布时间】:2010-09-09 13:24:31
【问题描述】:

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

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

【问题讨论】:

  • 如何区分数据中的逗号和分隔数据的逗号?
  • 因为这个问题最终会被谷歌索引为那些关键字。最好在顶部附近有更完整的答案。
  • 我认为,如果您想问一个不同的问题(或相同的问题,但有更多的细节),您应该这样做,而不是劫持这个问题并让它看起来像解决原始问题的答案提问者的问题是错误的。
  • 确实,我可以保证数据中没有逗号,所以我的问题可接受的答案是我接受的答案,string[] splitString = origString.Split(',');如果没有保证,我可以看到正则表达式方法的价值......

标签: c# string csv


【解决方案1】:

String.Split 只是不会削减它,但 Regex.Split 可能 - 试试这个:

using System.Text.RegularExpressions;

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

其中“输入”是 csv 行。这将处理带引号的分隔符,并应返回代表行中每个字段的字符串数组。

【讨论】:

  • 作为记录,这个正则表达式在我使用的数据上效果很好,它用逗号引用了数据。
  • 这不适用于未引用的数据(如果有的话):例如它在以下情况下失败: String s = "a,b,c";
  • 这是否适用于具有多行/记录的 csv 文件?
【解决方案2】:

如果您想要强大的 CSV 处理,请查看FileHelpers

【讨论】:

  • FileHelpers 是一个用于分隔和固定长度记录的出色库。使用 CSV 文件轻而易举。
【解决方案3】:
string[] splitString = origString.Split(',');

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

【讨论】:

  • 有编辑权限的人请修复这篇文章中的代码。
  • 如果您指的是需要 .Split({','}),在 C# 和 .NET 2.0 中,这不是必需的。我正在使用的 .Split(..) 重载需要一个参数 char[],编译器将它变成一个数组。
  • 这怎么可能是答案......因为这个问题清楚地表明用逗号分割还不够好?
  • 问题可能不太清楚,但是用逗号分割就足够了,因为我可以保证数据中没有逗号
  • 问题中加粗的部分不是原发帖人添加的,对他不需要的问题增加了不必要的要求。允许用户更改问题是我认为 Stack Overflow 需要解决的一个大问题。
【解决方案4】:

试试:

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

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

【讨论】:

    【解决方案5】:

    您可以看看使用 Microsoft.VisualBasic 程序集与

    Microsoft.VisualBasic.FileIO.TextFieldParser
    

    它处理带引号的 CSV(或任何分隔符)。我最近发现它很方便。

    【讨论】:

      【解决方案6】:

      如果您想使用嵌入的逗号来说明带引号的元素,尤其是当它们与未带引号的字段混合时,没有一种简单的方法可以很好地做到这一点。

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

      我的代码有几百行。

      我觉得网上有一些例子,开源项目等等。

      【讨论】:

        【解决方案7】:

        试试这个;

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

        【讨论】:

          【解决方案8】:
          CsvString.split(',');
          

          【讨论】:

          • 如果数据中有逗号?
          • 然后 String.split(", ");如果数据包含逗号和空格,那么 csv 是存储和传输数据的糟糕选择
          【解决方案9】:

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

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

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

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

          【讨论】:

          • 我想我们正在寻找单行,csv to value sets array
          • 补充说...我认为这个问题模棱两可。
          【解决方案10】:
          string s = "1,2,3,4,5";
          
          string myStrings[] = s.Split({','}};
          

          注意,Split() 需要一个 array 字符来分割。

          【讨论】:

          • 它需要一个params char[],这意味着你不需要创建char数组,编译器会为你做的
          【解决方案11】:

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

          【讨论】:

          • 例如,如果您有 Excel,请创建一个新文档并将数据输入到带有逗号的字段中。另存为 CSV 文件,然后在文本编辑器中打开它。对 mmattax 的启示。
          【解决方案12】:

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

          如果你想要一个你可以使用、免费或承诺的,这里是我的,它也做 IDataReader/Record。它还使用 DataTable 来定义/转换/强制列和 DbNull。

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

          它还没有引号。几天前我刚把它扔在一起挠痒痒。

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

          【讨论】:

          【解决方案13】:

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

          离暴露分隔符/修剪空间/类型 ig 仅几步之遥,您只需要窃取代码即可。

          【讨论】:

            【解决方案14】:

            我已经在标签上拆分,所以这对我有用:

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

            【讨论】:

              【解决方案15】:
              string test = "one,two,three";
              string[] okNow = test.Split(',');
              

              【讨论】:

                【解决方案16】:
                separationChar[] = {';'}; // or '\t' ',' etc.
                var strArray = strCSV.Split(separationChar);
                

                【讨论】:

                  【解决方案17】:
                  string[] splitStrings = myCsv.Split(",".ToCharArray());
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2019-10-10
                    • 2013-05-05
                    • 2019-01-05
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多