交叉表 行转列 方法

        /// <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/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值