时间:2023-01-10 11:52:49 | 栏目:.NET代码 | 点击:次
public static DataTable RevertRowToColumn(DataTable sourcedt) { DataTable dt = new DataTable(); //转换后的第一列名,以后此列每行存放sourcedt对应对应的每列列名 dt.Columns.Add("COLUMN_NAME", typeof(string)); //第二行及以后,转换后重命名的列名,列数等于sourcedt行数 string[] aa = new string[sourcedt.Rows.Count]; //string[] aa = { "VLAUE_1", "VLAUE_2", "VLAUE_3", "VLAUE_4", "VLAUE_5", "VLAUE_6", "VLAUE_7", "VLAUE_8", "VLAUE_9", "VLAUE_10" }; for (int i = 0; i < sourcedt.Rows.Count; i++) { aa[i] = "VLAUE_" + (i + 1); } //dt添加Columns for (int i = 0; i < aa.Length; i++) { dt.Columns.Add(aa[i].ToString(), typeof(string));//统一按照string类型进行存放 } //对sourcedt进行转换 for (int j = 0; j < sourcedt.Columns.Count; j++) { DataRow dr = dt.NewRow(); string column_name = sourcedt.Columns[j].ColumnName; dr["COLUMN_NAME"] = column_name;//把source的列名赋值给转换成行的第一列值 for (int i = 0; i < sourcedt.Rows.Count; i++) { string cell_value = sourcedt.Rows[i][column_name].ToString(); dr[i + 1] = cell_value; } dt.Rows.Add(dr); } return dt; }
转置前:
转置后:
注意:此转换的每列列类型统一为:typeof(string)类型。