【问题标题】:c# reading in a text file into datatablec# 将文本文件读入数据表
【发布时间】:2010-12-20 18:15:19
【问题描述】:

我需要将类似这样的文件读入数据表:

A02   BLANK031  
B02   F357442   
C02   F264977   
D02   BLANK037  
E02   F272521   
F02   E121562   
G02   F264972   
H02   F332321   
A03   E208240   
B03   F313854   
C03   E229786   
D03   E229787   
E03   F307584   
F03   F357478   

我有一个奇怪的分隔符和一些尾随空格。 我如何将其读入数据表,使第一列包含“A02”、“B02”……第二列包含“BLANK031”、“F357442”等。

目前我正在做:

DataTable dt = new DataTable();
                using (TextReader tr = File.OpenText(batchesAddresses[index]))
                {
                    string line;
                    while ((line = tr.ReadLine()) != null)
                    {

                    string[] items = Regex.Split(line, ' ');
                    if (dt.Columns.Count == 0)
                    {
                        // Create the data columns for the data table based on the number of items
                        // on the first line of the file
                        for (int i = 0; i < items.Length; i++)
                            dt.Columns.Add(new DataColumn("Column" + i, typeof(string)));
                    }
                        dt.Rows.Add(items);

                    }
                }

但这不起作用,因为我在列之间有尾随空格和多个空格

【问题讨论】:

  • 对于什么数据库?大多数都可以从平面文件中导入数据,而无需 C#/Java/等。
  • @omg 它们是文本文件,它不是来自数据库
  • 我说你要重新发明轮子

标签: c# delimiter


【解决方案1】:

如果你使用:

static readonly char[] space = { ' ' };
...
string[] items = line.Split(space, StringSplitOptions.RemoveEmptyEntries);

您应该得到您期望的 2 个值,尽管可能需要更具选择性的值,特别是如果右侧可能在中间包含一个空格。

【讨论】:

  • 谢谢,但我收到这些错误:错误 1 ​​'string.Split(params char[])' 的最佳重载方法匹配有一些无效参数,错误 2 参数 '2':无法从'System.StringSplitOptions' 到 'char'
【解决方案2】:

将您的正则表达式更改为:(\w{3})\s+(\w{5,10})。这意味着将 3 个单词字符(包括数字)捕获到第 1 组,查找一个或多个空白字符,然后将 5-10 个单词字符捕获到第 2 组。

然后做:

Regex r = new Regex("(\w{3})\s+(\w{5,10})");
Match m = r.Match(line);
string col1 = m.Groups[1].Value;
string col2 = m.Groups[2].Value;

【讨论】:

    【解决方案3】:

    关于 System.StringSplitOptions 的错误似乎是编译器中的一个转换错误。在 split 语句之前添加一行定义所需的 StringSplitOptions,然后在 split 语句中使用该变量。

    static readonly char[] space = { ' ' };
    static readonly StringSplitOptions options =  StringSplitOptions.RemoveEmptyEntries;
    ...
    string[] items = line.Split(space, options);
    

    这应该适用于所有重载。

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 2014-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-05
      • 1970-01-01
      相关资源
      最近更新 更多