简体   繁体   English

如何从其他数据表的行向数据表添加列

[英]How do i add columns to datatable from rows from another datatable

I have a DataTable called dt which is filled with values from excel. 我有一个名为dt的数据表,其中填充了来自excel的值。

On line 6 (row) i have my header information 在第6行(行)上,我有我的标题信息

Code i have now 我现在有密码

   string connString = @"Provider=Microsoft.ACE.OLEDB.16.0;Data Source=C:\Users\thoje\Desktop\stack\forslag.xlsx;" +
        @"Extended Properties=""Excel 12.0;HDR=No;""";
        DataTable dt = new DataTable();

        string sql = @"SELECT * from [Ark1$]";
        using (OleDbConnection conn = new OleDbConnection(connString))
        {
            conn.Open();
            using (OleDbCommand cmd = new OleDbCommand(sql, conn))
            {
                using (OleDbDataReader rdr = cmd.ExecuteReader())
                {
                    dt.Load(rdr);



                }
            }
        }
        DataTable dt2 = dt.Clone();



        //foreach (DataRow dr in dt.Rows)
        //{

        for (int i = 5; i <= dt.Rows.Count-1; i++)
        {


            if (i == 6)
            {
                DataRow dr = dt2.NewRow();
                dr.ItemArray = dt.Rows[i].ItemArray;
                dt2.Rows.Add(dr);

            }


            else if(i >=8)
            {
                DataRow dr = dt2.NewRow();
                dr.ItemArray = dt.Rows[i].ItemArray;
                dt2.Rows.Add(dr);
            }
        }

What i need is: 我需要的是:

  1. I want all my data on row 6 to become headers in a new DataTable 我希望第6行上的所有数据成为新DataTable中的标题
  2. All data after line 7 i need to append to this new Datatable with the new headers. 第7行之后的所有数据我都需要使用新的标头附加到此新的Datatable中。

What my code shows: 我的代码显示了什么:

My code now shows how to do it on a DataTable which is cloned, so therefore i have the wrong headernames. 我的代码现在显示了如何在克隆的DataTable上执行此操作,因此我的头名错误。

You don't need to iterate through all rows if you only need 1 of them. 如果只需要其中一行,则不需要遍历所有行。

DataTable dtSource = new DataTable();
DataTable dtTarget = new DataTable();

// Get row at index == 6 (7th line as this is a 0-based-index)
var headerRow = dtSource.Rows[6];

// Iterate through all values
foreach(var value in headerRow.ItemArray)
{
    // For each value create a column
    // and add it to your new dataTable
    DataColumn dc = new DataColumn(value.ToString());
    dc.Caption = value.ToString();
    dtTarget.Columns.Add(dc);
}

using a linq approach might be good: a pseudo way: 使用linq方法可能会很好:伪方式:

 //linq query to select row 
 var query = from myRow in
 myDataTable.AsEnumerable() where myRow.Field<int>("RowNo") == 6 
 select myRow;

// Create a table from the query DataTable newTable =
query.CopyToDataTable<DataRow>();

Your question is pretty confusing to read, and keeps talking about rows where I'd expect columns etc, but I'll make the following assumptions: 您的问题很难看清,并且一直在谈论我期望列等的行,但是我将做出以下假设:

  • You have an excel file with 5 blank rows and then a row of headers, and then data rows 您有一个Excel文件,其中包含5个空白行,然后是标题行,然后是数据行
  • You've successfully imported this data into a Datatable called dt 您已成功将此数据导入到名为dt的数据表中
  • You want to end up with a datatable that has the values in row 6 as the column names, and the blank rows removed 您希望最终得到一个数据表,该表具有第6行中的值作为列名,并删除了空白行

Code: 码:

for(int i = 5; i >= 0; i--){
  if(i == 5)
  {
    for(int j = 0; j < dt.Columns.Count; j++)
      dt.Columns[j].ColumnName = dt.Rows[i][j].ToString();
  }
  dt.Rows.RemoveAt(i);
}

You don't need to clone the datatable. 您无需克隆数据表。 Watch out for strings that make for poor column names (containing chars like '[' ) making your life miserable further down the line .. 当心那些导致较差列名的字符串(包含诸如“ [”)之类的字符,使您的生活更加痛苦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM