/// <summary>
/// 将DataTable的第二列的值转化为列(即将原来的行表,转化成交叉表,没有对应值则默认"0")
/// </summary>
/// <param name="dt">必须三列,第三列为值</param>
/// <returns></returns>
public static DataTable GetCrossTable(DataTable dt)
{
if (dt == null || dt.Columns.Count != 3 || dt.Rows.Count == 0)
{
return dt;
}
else
{
DataTable result = new DataTable();
result.Columns.Add(dt.Columns[0].ColumnName);
DataTable dtColumns = dt.DefaultView.ToTable("dtColumns", true, dt.Columns[1].ColumnName);
for (int i = 0; i < dtColumns.Rows.Count; i++)
{
string colName;
if (dtColumns.Rows[1][0] is DateTime)
{
colName = Convert.ToDateTime(dtColumns.Rows[i][0]).ToString(Constants.DATE_FORMART);
}
else
{
colName = dtColumns.Rows[i][0].ToString();
}
result.Columns.Add(colName);
result.Columns[i + 1].DefaultValue = "0";
}
DataRow drNew = result.NewRow();
drNew[0] = dt.Rows[0][0];
string rowName = drNew[0].ToString();
foreach (DataRow dr in dt.Rows)
{
string colName = dr[1].ToString();
double dValue = Math.Round(GetDoubleValue(dr[2], 0), 2);
if (dr[0].ToString().Equals(rowName, StringComparison.CurrentCultureIgnoreCase))
{
drNew[colName] = dValue.ToString();
}
else
{
result.Rows.Add(drNew);
drNew = result.NewRow();
drNew[0] = dr[0];
rowName = drNew[0].ToString();
drNew[colName] = dValue.ToString();
}
}
result.Rows.Add(drNew);
return result;
}
}
试用登录 http://121.18.78.216/
/// 将DataTable的第二列的值转化为列(即将原来的行表,转化成交叉表,没有对应值则默认"0")
/// </summary>
/// <param name="dt">必须三列,第三列为值</param>
/// <returns></returns>
public static DataTable GetCrossTable(DataTable dt)
{
if (dt == null || dt.Columns.Count != 3 || dt.Rows.Count == 0)
{
return dt;
}
else
{
DataTable result = new DataTable();
result.Columns.Add(dt.Columns[0].ColumnName);
DataTable dtColumns = dt.DefaultView.ToTable("dtColumns", true, dt.Columns[1].ColumnName);
for (int i = 0; i < dtColumns.Rows.Count; i++)
{
string colName;
if (dtColumns.Rows[1][0] is DateTime)
{
colName = Convert.ToDateTime(dtColumns.Rows[i][0]).ToString(Constants.DATE_FORMART);
}
else
{
colName = dtColumns.Rows[i][0].ToString();
}
result.Columns.Add(colName);
result.Columns[i + 1].DefaultValue = "0";
}
DataRow drNew = result.NewRow();
drNew[0] = dt.Rows[0][0];
string rowName = drNew[0].ToString();
foreach (DataRow dr in dt.Rows)
{
string colName = dr[1].ToString();
double dValue = Math.Round(GetDoubleValue(dr[2], 0), 2);
if (dr[0].ToString().Equals(rowName, StringComparison.CurrentCultureIgnoreCase))
{
drNew[colName] = dValue.ToString();
}
else
{
result.Rows.Add(drNew);
drNew = result.NewRow();
drNew[0] = dr[0];
rowName = drNew[0].ToString();
drNew[colName] = dValue.ToString();
}
}
result.Rows.Add(drNew);
return result;
}
}
试用登录 http://121.18.78.216/