【问题标题】:Delimited text to DataTable分隔文本到 DataTable
【发布时间】:2019-03-22 19:05:08
【问题描述】:

我有一个制表符分隔文件,我想在 DataGridView (DGV) 中加载它;为此,我使用以下代码:

DataTable dt = new DataTable();
using (FileStream stream = File.OpenRead("logs.txt"))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        string line = reader.ReadLine();

        while (line != null)
        {
            string[] items = line.Split('\t');
            line = reader.ReadLine();

            if (dt.Columns.Count == 0)
            {
                for (int i = 0; i < items.Length; i++)
                {
                    dt.Columns.Add("Column " + i);
                }
            }
            dt.Rows.Add(items);
        }
        dataGridView1.DataSource = dt;
    }
}

问题在于每行的列数并不总是相同,这会产生错误“输入数组比此表中的列长”。

文字示例:

x   xx  xxx xxxx    xxxxx
x   xx  xxx xxxx    xxxxx   xxxxxx  xxxxxxx
x   xx  xxx xxxx    xxxxx   xxxxxx  xxxxxxx xxxxxxxx    xxxxxxxxx

鉴于问题,我该如何将所有文本文件传递给 DGV?

【问题讨论】:

  • 有没有办法计算出文件可以有多少列的最大数量?是否有任何标准或规则可以确保文件中只有特定数量的列?
  • @ChetanRanpariya 遗憾的是,不,这就是让这有点复杂的原因:(

标签: c# .net parsing datagridview csv


【解决方案1】:

首先,您应该尝试通过阅读异常来理解异常,并弄清楚这个异常是在什么情况下引发的。

然后调试代码,了解为什么会从您的代码中引发此异常,并尝试了解如何解决此问题。

无论如何,回到你的代码。

仅当dt.Columns.Count 为零时,您才向表中添加新列。因此,将仅为文件的第一行添加列,因为在某个时间点没有列。并且文件第一行的值将成功添加到表中。

之后它将不会添加新列,并且当您尝试向该行添加值时,您会遇到异常,因为现在该行中的项目数与表中的列数不同。

因此从逻辑上讲,您需要检查该行中的项目数是否大于数据表中当前的列数。如果是,则在数据表中添加这些额外的列数。

并且也不要使用dt.Rows.Add,而是将值逐一添加到行中。

考虑以下代码。

DataTable dt = new DataTable();
using (FileStream stream = File.OpenRead("logs.txt"))
{
    using (StreamReader reader = new StreamReader(stream))
    {
        string line = reader.ReadLine();

        while (line != null)
        {
            string[] items = line.Split(',');

            // Check if the number of items in the line is 
            // greater than the current number of columns in the datatable.
            if(items.Length > dt.Columns.Count)
            {
                // Add new columns to the datatable.
                for (int i = dt.Columns.Count; i < items.Length; i++)
                {
                    dt.Columns.Add("Column " + i);
                }
            }

            // Create new row
            var newRow = dt.NewRow();

            // Loop thru the items and add them to the row one by one.
            for (var j = 0; j < items.Length; j++)
            {
                newRow[j] = items[j];
            }

            //Add row to the datatable.
            dt.Rows.Add(newRow);
            line = reader.ReadLine();
        }
        // Bind datatable to the gridview.
        dataGridView1.DataSource = dt;
    }
}

这应该可以帮助您解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 2010-09-22
    • 2020-03-05
    • 2020-06-28
    相关资源
    最近更新 更多