1 private string ExportExcel(DataPager dataPagerTemp, DataGrid dataGridTemp) 2 { 3 string colPath; 4 System.Reflection.PropertyInfo propInfo; 5 System.Windows.Data.Binding binding; 6 System.Text.StringBuilder strBuilder = new System.Text.StringBuilder(); 7 //加载Excel表头数据 8 List<string> headers = new List<string>(); 9 for (int i = 0; i < dataGridTemp.Columns.Count; ++i) 10 { 11 string strTemp = dataGridTemp.Columns[i].Header.ToString(); 12 headers.Add(FormatCSVField(strTemp)); 13 14 } 15 strBuilder.Append(String.Join("", headers.ToArray())) 16 .Append("\t\n"); 17 18 //内容 19 for (int i = 0; i < dataPagerTemp.PageCount; i++) 20 { 21 dataPagerTemp.PageIndex = i; 22 23 foreach (Object m_Temp in dataGridTemp.ItemsSource) 24 { 25 List<string> csvRow = new List<string>(); 26 27 foreach (DataGridColumn col in dataGridTemp.Columns) 28 { 29 if (col is DataGridBoundColumn) 30 { 31 binding = (col as DataGridBoundColumn).Binding; 32 colPath = binding.Path.Path; 33 string[] pathlist = colPath.Split('.'); 34 35 object currentData = m_Temp; 36 int count = 0; 37 foreach (string item in pathlist) 38 { 39 propInfo = currentData.GetType().GetProperty(item); 40 if (propInfo == null) break; 41 count++; 42 if (count == pathlist.Length) 43 { 44 csvRow.Add(FormatCSVField(propInfo.GetValue(currentData, null).ToString())); 45 break; 46 } 47 else 48 { 49 currentData = propInfo.GetValue(currentData, null); 50 } 51 52 } 53 54 } 55 } 56 strBuilder 57 .Append(String.Join("", csvRow.ToArray())) 58 .Append("\t\n"); 59 } 60 } 61 dataPagerTemp.PageIndex = 0; 62 return strBuilder.ToString(); 63 }
设置假翻页控件的当前页,然后从DG里获取Sources,foreach DG.Coloumns 里面是在干什么?? 分割bing.Path.path 后的又是啥?为什么要遍历它 累积属性的值 才把这最终的值当作1列?
这段代码好丑。
1.根据DataGrid每列绑定的属性,从Source的元素中取出这些属性的值。
2.binding.Path.Path就是绑定的Property链。
3.为啥说好丑呢?遍历Binding应该在最外的循环外面,并且将每列的Property链保存起来,而不是每次都去取一遍。可能是因为这个原因所以你糊涂了。