4

I Use the following code for load the sql table values into the datatable

        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection("Connection String Here");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from ExportExcel", con);
        dt.Load(cmd.ExecuteReader());
        int total = 0;
        foreach (DataRow row in dt.Rows)
        {
            int salaryvalue = Convert.ToInt32(row["Salary"]);
            total = salaryvalue + total;
        }

        dt.Rows.Add("Salary");
        dt.Rows.Add(total);

And I add Salary,total dynamically.But It Shows in first column one by one.

enter image description here

But I need salary in Department column,and total in Salary Column.How to do this? enter image description here

4

5 回答 5

4

您可以使用

     dt.rows.add(new object[]{"","Salary",total });

您可以使用而不是计算总计Datatable.Compute Method

     object total;
      total= dt.Compute("Sum(Salary)", "");
于 2013-10-11T10:00:45.627 回答
0

你应该在你的 foreach 循环之后这样写,

DataRow drNew=dt.NewRow();
drNew[0]="";
drNew[1]="Salary";
dtNew[2]=total;
dt.Rows.Add(drNew);

希望这可以帮助

于 2013-10-11T10:02:33.983 回答
0

您实际上只想添加一行,因此只需添加一行。

dt.Rows.Add(string.Empty, "Salary", total);
于 2013-10-11T10:03:52.210 回答
0

您需要的 ADO.NET 信息可以在 msdn: DataRow中找到。您可以像您所做的那样在代码中计算它,也可以在 excel 文档中插入一个函数。

DataRow row = dt.NewRow();

row["Name"] = "Salary";
row["Salary"] = total;
dt.Rows.Add(row);
于 2013-10-11T10:03:55.320 回答
0

首先,不要*在您的查询中使用,这只会在将来产生令人讨厌的错误。命名您要检索的所有列。

您必须为第一列添加一个空字符串:

// dt.Rows.Add("Salary"); <-- remove
dt.Rows.Add("", "Salary", total);

顺便说一句,您还可以使用以下查询来获取总数:

int total = dt.AsEnumerable.Sum(r => r.Field<int>("Salary"));
于 2013-10-11T10:04:18.430 回答