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 = 0; 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 + 1]; newRow[0] = col.ColumnName; for (int i = 0; i < src.Rows.Count; i++) { newRow[i + 1] = src.Rows[i][col]; } result.Rows.Add(newRow); } return result; } public static DataTable Col2Row(DataTable src, string columnHead) { for (int i = 0; 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"] = 1; dr["col02"] = 2; dr["Col03"] = 3; dt.Rows.Add(dr); DataRow dr2 = dt.NewRow(); dr2["Col01"] = 4; dr2["col02"] = 5; dr2["Col03"] = 6; dt.Rows.Add(dr2); DataRow dr3 = dt.NewRow(); dr3["Col01"] = 7; dr3["col02"] = 8; dr3["Col03"] = 9; dt.Rows.Add(dr3); return dt; } private static DataTable Col2Row(DataTable dt) { DataTable result = new DataTable(); for (int i = 0; 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 + 1]; newRow[0] = col.ColumnName; for (int i = 0; i < dt.Rows.Count; i++) { newRow[i + 1] = dt.Rows[i][col]; } result.Rows.Add(newRow); } return result; } } }
关于行列转换,记下来,免得以后要用在写。