两列数据转换成四列数据,
三列数据转换成六列数据,
/// <summary>
/// DataTable 列转换为N倍列,减少行数
/// </summary>
/// <param name="dataTable"></param>
/// <param name="multiple"></param>
/// <returns></returns>
public DataTable DtToMultipleCol(DataTable dataTable, int multiple = 2)
{
DataTable dt = new DataTable();
//dataTable行数
int rows = dataTable.Rows.Count;
//dt行数
int dtRows = rows % multiple == 0 ? rows / multiple : rows / multiple + 1;
//dataTable列数
int cols = dataTable.Columns.Count;
//dt列数
int dtCols = cols * multiple;
if (rows > 0)
{
for (int i = 0; i < dtCols; i++)
{
//循环向dt中增加列
dt.Columns.Add("col" + i, typeof(string));
}
DataRow dr = dt.NewRow();
bool flag = false;
int k = 0; //向量
for (int i = 0; i < rows; i++)
{
if (i % multiple == 0)
{
k = 0;
dr = dt.NewRow();
for (int j = 0; j < dtCols / multiple; j++)
{
dr[j] = dataTable.Rows[i][j].ToString();
}
flag = true;
}
else
{
//以cols的倍数往后填充数据
for (int j = dtCols / multiple + k++ * cols; j < cols * (k + 1); j++)
{
dr[j] = dataTable.Rows[i][j % cols].ToString();
}
//dr行数据填充完毕
if ((i + 1) % multiple == 0)
{
dt.Rows.Add(dr);
flag = false;
}
}
}
//dr行数据未填充满
if (flag)
{
dt.Rows.Add(dr);
}
}
return dt;
}