Silverlight DataGrid: Export to excel or csv

后端 未结 9 2205
野趣味
野趣味 2020-12-13 10:17

Is there a way I can export my Silverlight DataGrid data to excel or csv?

I searched the web but can\'t find any examples!

Thanks a lot

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 10:44

    Those solutions didn't work for me, so I modified them to one that worked. (My solution doesn't require quotes around fields, so I left out the FormatCSVField function)

        public void SaveAs(string csvPath)
        {
            string data = ExportDataGrid(true, _flexGrid);
            StreamWriter sw = new StreamWriter(csvPath, false, Encoding.UTF8);
            sw.Write(data);
            sw.Close();
        }
    
        public string ExportDataGrid(bool withHeaders, Microsoft.Windows.Controls.DataGrid grid) 
        {
            System.Text.StringBuilder strBuilder = new System.Text.StringBuilder();
            System.Collections.IEnumerable source = (grid.ItemsSource as System.Collections.IEnumerable);
    
            if (source == null) return "";
    
            List headers = new List();
    
            grid.Columns.ToList().ForEach(col =>
            {
                if (col is Microsoft.Windows.Controls.DataGridBoundColumn)
                {
                    headers.Add(col.Header.ToString());
                }
            });
    
            strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
            foreach (Object data in source)
            {
                System.Data.DataRowView d = (System.Data.DataRowView)data;
                strBuilder.Append(String.Join(",", d.Row.ItemArray)).Append("\r\n");
            }
    
            return strBuilder.ToString();
        }
    

提交回复
热议问题