将一个数据表选定列复制到另一个数据表

时间:2014-04-29 05:59:14

标签: asp.net

我有一个数据表,然后我将数据表的所有列名称作为复选框,我只想显示那些用户从复选框中选择的列记录:
下面是代码,但我没有得到理想的结果

var values = "";
            string clmnm = "";
            for (int i = 0; i < interestedIN.Items.Count; i++)
            {
                if (interestedIN.Items[i].Selected)
                {
                    values += interestedIN.Items[i].Value + ",";
                }
            }

            values = values.TrimEnd(',');
            string[] words = values.Split(',');



            DataTable dt = new DataTable();
            dt = (DataTable)Session["dataset"];
            DataTable dt1 = new DataTable();
            foreach (string word in words)
            {
                dt1.Columns.Add(word, typeof(string));
                if (clmnm == string.Empty)
                {
                    clmnm = word.Trim();
                }
                else
                {
                    clmnm += "," +word.Trim();
                }
              }
            foreach (DataRow dr in dt.Rows)
            {
                string[] split = clmnm.Split(',');
                int j =0;
                string str = "";
                string str2 = "";
                while( j < split.Length)
                {
                    str = split[j].ToString();
                    if (str2 == string.Empty)
                    {
                        str2 = "dr[\""+str.ToString()+"\"]";
                    }
                    else
                    {
                        str2 += "," + "dr[\""+str.ToString()+"\"]";
                    }

                    j+=1;
                 }
                dt1.Rows.Add(str2);         
            }  

然后我尝试将结果导出为Excel工作表:但获取以下Excel工作表:
enter image description here

1 个答案:

答案 0 :(得分:1)

您的代码需要做很多更改。让我们从CheckBoxList中的选定列开始。尝试使用ListArray来存储用户想要的列。像

List<string> columns = new List<string>();

然后将所选列存储到columns列表中。然后,您需要为新的DataTable dt1添加列。如,

DataTable dt1 = new DataTable();
for (int i = 0; i < interestedIN.Items.Count; i++)
{
     if (interestedIN.Items[i].Selected) //If user selected this columns checkbox.
     {
         columns.Add(interestedIN.Items[i].Text.Trim()); //Storing values to List.
         dt1.Columns.Add(interestedIN.Items[i].Text.Trim()); //Adding columns to the DataTable.
     }
}

然后,您可以循环浏览原始DataTable dt并将值存储如下。

foreach (DataRow dr in dt.Rows)
{
   DataRow dr1 = dt1.NewRow(); // Create new row which should have identical structure for inserting.
   foreach(string col in columns)
   {
      dr1(col) = dr(col);
   }
   dt1.Rows.Add(dr1); //Add the row with the contents to the table.
}