分隔文本到DataTable

时间:2018-10-18 02:29:09

标签: c# .net parsing datagridview tab-delimited

我有一个制表符分隔的文件,我想将其加载到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?

1 个答案:

答案 0 :(得分: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;
    }
}

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