2013-10-11 32 views
4

我使用負載下面的代碼SQL表值到數據表下添加特定列一列數據表

 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); 

我加工資,總dynamically.But它通過一個顯示在首列的一個。

enter image description here

但我需要在系列的工資,並在總薪酬Column.How做到這一點? enter image description here

回答

4

可以使用

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

代替計算總的可以使用Datatable.Compute Method

 object total; 
     total= dt.Compute("Sum(Salary)", ""); 
0

您應該在foreach循環後這樣寫,

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

希望這幫助

0

您實際上只想添加一行,因此只需添加一行即可。

dt.Rows.Add(string.Empty, "Salary", total); 
0

您需要的ADO.NET信息可以在msdn:DataRow找到。你可以用代碼來計算它,就像你已經完成的那樣,或者在Excel文檔中插入一個函數。

DataRow row = dt.NewRow(); 

row["Name"] = "Salary"; 
row["Salary"] = total; 
dt.Rows.Add(row); 
+1

呵呵..太逗了,或者真的很難過,那些可以很容易地回答的問題(通過查找msdn)總能得到很多答案,而那些難以回答的問題會因爲他們沒有得分/分鐘而受到影響。 – Mithon

0

首先,不要在您的查詢,在今後的生產只是討厭的錯誤使用*。命名您想要檢索的所有列。

您必須添加一個空字符串爲第一列:

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

順便問一下,你也可以使用下面的查詢,以獲得總數:

int total = dt.AsEnumerable.Sum(r => r.Field<int>("Salary")); 
相關問題