1、调整DataTable列的顺序
dt.Columns[1].SetOrdinal(0); //将第1列改成第0列
2、复制DataRow
使用Add方法复制DataRow时会遇到该行已属于另一个表,用ImportRow就可以了。
dt.ImportRow(row);
3、行列倒置函数
public static DataTable ColumnToRow(DataTable src_dt, int columnIndex) //columnIndex 用来当作新列名的列
{
DataTable dt = new DataTable();
dt.Columns.Add(src_dt.Columns[columnIndex].ColumnName);
List<string> lstColumnName = new List<string>();
foreach (DataRow dr in src_dt.Rows)
{
if (lstColumnName.Contains(dr[columnIndex].ToString())) continue;
if (dr[columnIndex].ToString() == string.Empty) continue;
lstColumnName.Add(dr[columnIndex].ToString());
dt.Columns.Add(dr[columnIndex].ToString());
}
int n = src_dt.Columns.Count;
for (int i = 0; i < n; i++)
{
if (i == columnIndex) continue; //如果是被当作列名的列,则跳过
DataRow new_dr = dt.NewRow();
string columnName = src_dt.Columns[i].ColumnName;
new_dr[0] = columnName;
foreach (DataRow dr in src_dt.Rows)
{
if (dr[columnIndex].ToString() == string.Empty) continue;
string newColumnName = dr[columnIndex].ToString();
new_dr[newColumnName] = dr[columnName];
}
dt.Rows.Add(new_dr);
}
return dt;
}