如何在数据集中将两个数据列合并为一个

问题描述

我将 Excel 文件作为输入,并使用 ExcelDataReader 将其转换为数据集。问题是,在这文件中可能有同名的列。 我不会事先知道列名,因为它们会根据源文件而改变,但我知道对于每一行,只有其中任何一行都有一个值。 这是源文件可能是什么的示例:

CellH ... CellH ... Glass_L ... Glass_L
123 ... ... 456 ...
... 321 ... ... 654

ExcelDataReader 通过在列名中附加“_1”但保留 DataColumn.Caption 属性作为原始列名来处理重复的列名。 在示例中,数据集将如下所示:

CellH ... CellH_1 ... Glass_L ... Glass_L_1
123 ... ... 456 ...
... 321 ... ... 654

空格是 dbnull 类型,其他都应该是字符串。

我需要实现的是合并所有具有相同名称的列(现在是标题) 像这样:

CellH ... ... Glass_L ...
123 ... ... 456 ...
321 ... ... 654 ...

现在我想做的是获取一个带有重复标题的列表,并以某种方式使用 this method 迭代它来连接列的值。问题是我可能有多个具有重复名称的不同列,但我不知道如何处理 dbnull 值。 到目前为止,这是我的代码

public static DataTable AbacoMerger(DataSet collection)
    {
        DataTable dt = new DataTable("Abaco");
        var headers = new List<string>();
        var duplicates = new List<string>();

        dt.Columns.Add(new DataColumn() // Unique column Id
        {
            ColumnName = "Abaco_ID",DataType = Type.GetType("system.int32"),AutoIncrement = true,AutoIncrementSeed = 1,Allowdbnull = false,Unique = true,});

        // Serch for duplicate captions
        for (int i = 0; i < collection.Tables[0].Columns.Count; i++)
            headers.Add(collection.Tables[0].Columns[i].Caption);
        for (int i = 0; i < headers.Count; i++) 
            for (int j = i + 1; j < headers.Count; j++)
                if (headers[i] == headers[j])
                    duplicates.Add(headers[j]);

        if (duplicates.Count > 0)
        {
            collection.Tables[0].MergeColumns( ??? );
        }

        // Create the columns in the DataTable using the DataSet headers and DataType (should be all string)
        for (int i = 0; i < collection.Tables[0].Columns.Count; i++)
        {
            dt.Columns.Add(collection.Tables[0].Columns[i].ColumnName,collection.Tables[0].Columns[i].DataType);
        }

        // Imports all the rows from the DataSet to the new DataTable
        foreach (DataTable table in collection.Tables) 
        {
            for (int i = 0; i < table.Rows.Count; i++) 
            {
                if (table.Rows[i].ItemArray.All(o => o is dbnull))
                {
                    i++;
                }
                dt.ImportRow(table.Rows[i]);
            }
        }

        dt.PrimaryKey = new DataColumn[] { dt.Columns["Abaco_ID"] };

        return dt;
    }

public static void MergeColumns(this DataTable t,string newColumn,params string[] columnsToMerge)
    {
        t.Columns.Add(newColumn,typeof(string));

        var sb = new StringBuilder();

        sb.Append("{0},");
        for (int i = 1; i < columnsToMerge.Length; ++i)
            sb.Append("{" + i.ToString() + "}");

        string format = sb.ToString();

        foreach (DaTarow r in t.Rows)
            r[newColumn] = string.Format(format,columnsToMerge.Select(col => r[col]).ToArray());
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)