转置数据表 [英] Transpose a datatable

查看:81
本文介绍了转置数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的数据表。我想更改数据表以将数据表转换为旁边的数据表。我该怎么办?

I have the data table below. I would like to change the data table to transform the data table into the one next to it. How can I do this?

我之所以要这样做是因为excel文件将数据显示为如图所示,然后我希望对数据进行排序在第1行上

The reason why i would like o do this is because the excel file brings the data in like shown and then i would like to sort this data out on Row 1

当前表

      || Col 1 || Col 2 || Col 3
____________________________________    
Row 1 || 10    ||  20   || 30
Row 2 || 1     ||  2    || 3 

新数据表

      || Row 1 || Row 2 
Col 1 ||  10   ||   1
Col 2 ||  20   ||   2
Col 3 ||  30   ||   3


推荐答案

.NET不包含转置数据的方法表。你必须自己做。 网站上提供了有关示例转置方法的教程。我将复制并粘贴以下代码段:

.NET does not include a method to transpose data tables. You have to make your own. This website has a tutorial on an example transpose method. I will copy and paste the code snippet below:

private DataTable Transpose(DataTable dt)
{
    DataTable dtNew = new DataTable();

    //adding columns    
    for(int i=0; i<=dt.Rows.Count; i++)
    {
       dtNew.Columns.Add(i.ToString());
    }



    //Changing Column Captions: 
    dtNew.Columns[0].ColumnName = " ";

     for(int i=0; i<dt.Rows.Count; i++) 
     {
      //For dateTime columns use like below
       dtNew.Columns[i+1].ColumnName = Convert.ToDateTime(dt.Rows[i].ItemArray[0].ToString()).ToString("MM/dd/yyyy");
      //Else just assign the ItermArry[0] to the columnName prooperty
     }

    //Adding Row Data
    for(int k=1; k<dt.Columns.Count; k++)
    {
        DataRow r = dtNew.NewRow();
        r[0] = dt.Columns[k].ToString(); 
        for(int j=1; j<=dt.Rows.Count; j++)
        r[j] = dt.Rows[j-1][k];  
        dtNew.Rows.Add(r);
    }

 return dtNew;
}

这篇关于转置数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆