using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data; namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable dt = GetDt();
DataTable res = Col2Row(dt, "Col01");
DataTable test = Col2Row(dt);
} public static DataTable Col2Row(DataTable src, int columnHead)
{
DataTable result = new DataTable();
DataColumn myHead = src.Columns[columnHead];
result.Columns.Add(myHead.ColumnName);
for (int i = ; i < src.Rows.Count; i++)
{
result.Columns.Add(src.Rows[i][myHead].ToString());
}
//
foreach (DataColumn col in src.Columns)
{
if (col == myHead)
continue;
object[] newRow = new object[src.Rows.Count + ];
newRow[] = col.ColumnName;
for (int i = ; i < src.Rows.Count; i++)
{
newRow[i + ] = src.Rows[i][col];
}
result.Rows.Add(newRow);
}
return result;
} public static DataTable Col2Row(DataTable src, string columnHead)
{
for (int i = ; i < src.Columns.Count; i++)
{
if (src.Columns[i].ColumnName.ToUpper() == columnHead.ToUpper())
return Col2Row(src, i);
}
return new DataTable();
} private static DataTable GetDt()
{
DataTable dt = new DataTable();
dt.Columns.Add("Col01");
dt.Columns.Add("Col02");
dt.Columns.Add("Col03"); DataRow dr = dt.NewRow();
dr["Col01"] = ;
dr["col02"] = ;
dr["Col03"] = ;
dt.Rows.Add(dr); DataRow dr2 = dt.NewRow();
dr2["Col01"] = ;
dr2["col02"] = ;
dr2["Col03"] = ;
dt.Rows.Add(dr2); DataRow dr3 = dt.NewRow();
dr3["Col01"] = ;
dr3["col02"] = ;
dr3["Col03"] = ;
dt.Rows.Add(dr3); return dt;
} private static DataTable Col2Row(DataTable dt)
{
DataTable result = new DataTable();
for (int i = ; i < dt.Rows.Count; i++)
{
result.Columns.Add(i.ToString());
}
result.Columns.Add(dt.Rows.Count.ToString());
foreach (DataColumn col in dt.Columns)
{
object[] newRow = new object[dt.Rows.Count + ];
newRow[] = col.ColumnName;
for (int i = ; i < dt.Rows.Count; i++)
{
newRow[i + ] = dt.Rows[i][col];
}
result.Rows.Add(newRow);
}
return result;
} }
}

关于行列转换,记下来,免得以后要用在写。

datatable 行列转换-LMLPHP

datatable 行列转换-LMLPHP

datatable 行列转换-LMLPHP

05-07 15:38