从表到表复制列值,跳过前3行

时间:2012-11-15 09:37:39

标签: c# datatable copy two-columns

我有一个问题。我有2个DataTables,想要从第一个表复制3列到另一个表的3列。如何跳过3个第一行,然后将值添加到2.table?。

我的代码看起来像这样:

 foreach (DataRow ex1 in excelTb1.Rows)
            {
                foreach (DataRow ex2 in excelTb2.Rows)
                {                      

                    //ex2["ABC"] = ex1["ABC"];      // with skip(3) ?
                    //ex2["Name"] = ex1["Name"];
                    //ex2["ID"] = ex1["ID"];
                }
            }

我的1.table: _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ _ _我的2.table应该看起来像这样:

          Table1                               Table2
ABC   Name   ID  ...                     ABC   Name   ID    ...                     
 a     lola   2  ...                     ...   ...    ...   ... 
 b     kiki   6  ...                     ...   ...    ...   ... 
...    ...   ... ...                     ...   ...    ...   ... 
                                         a     lola   2     ...
                                         b     kiki   6     ...        
                                         ...   ...    ...   ...             

2 个答案:

答案 0 :(得分:2)

  

跳过前3行

使用For循环而不是foreach。

for(int i=3; i < excelTb2.Rows.Count; i++) //start the loop with index 3 => Row 4
{
    DataRow ex2 = exceltb2.Rows[i];
    //ex2["ABC"] = ex1["ABC"];      // with skip(3) ?
    //ex2["Name"] = ex1["Name"];
    //ex2["ID"] = ex1["ID"];
}

答案 1 :(得分:1)

for (int i = 0; i < excelTb1.Rows.Count; i++)
{
     DataRow dr1 = excelTb1.Rows[i];

     if (excelTb2.Rows.Count > i + 3)
     {
         DataRow dr2 = excelTb2.Rows[i + 3];
         dr2["ABC"] = dr1["ABC"];
         dr2["Name"] = dr1["Name"];
         dr2["ID"] = dr1["ID"];
     }
     else
         break;
}