Export datagrid to .csv in WPF

Serhat Özyıldız 21 Reputation points
2022-05-12T21:48:02.36+00:00

I have already a working code in WinForm but I want to convert it to WPF but I cannot do it because I am new in WPF. Can you guys try to convert it to WPF?

Here is my code in WinForms;

            if (myGrid.RowCount > 0)
            {
                string value = "";
                DataGridViewRow dr = new DataGridViewRow();
                StreamWriter sWriter = new StreamWriter(fileLocation);

                //write header rows to csv
                for (int i = 0; i <= myGrid.Columns.Count - 1; i++)
                {
                    if (i > 0)
                    {
                        sWriter.Write(",");
                    }
                    sWriter.Write(myGrid.Columns[i].HeaderText);
                }
                sWriter.WriteLine();

                //write DataGridView rows to csv
                for (int j = 0; j <= myGrid.Rows.Count - 1; j++)
                {
                    if (j > 0)
                    {
                        sWriter.WriteLine();
                    }

                    dr = myGrid.Rows[j];

                    for (int i = 0; i <= myGrid.Columns.Count - 1; i++)
                    {
                        if (i > 0)
                        {
                            sWriter.Write(",");
                        }

                        value = dr.Cells[i].Value.ToString();
                        //replace comma's with spaces
                        value = value.Replace(',', ' ');
                        //replace embedded newlines with spaces
                        value = value.Replace(Environment.NewLine, " ");

                        sWriter.Write(value);
                    }
                }
                sWriter.Close();
                MessageBox.Show("Exported succesfully.");
            }
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,671 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 38,251 Reputation points Microsoft Vendor
    2022-05-13T03:27:25.057+00:00

    For the case where the ItemsSource of the DataGrid is a collection, you could refer to the following code.
    MainWindow.xaml:

    <DockPanel>  
        <Button Content="Export data" Click="Export_Click" DockPanel.Dock="Bottom"/>  
        <DataGrid x:Name="dataGrid" ItemsSource="{Binding Products}" AutoGenerateColumns="False">  
            <DataGrid.Columns>  
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" />  
                <DataGridTextColumn Header="Id" Binding="{Binding Id}" />  
                <DataGridCheckBoxColumn Header="Checked" Binding="{Binding IsAvailable}"/>  
    
            </DataGrid.Columns>  
        </DataGrid>  
    </DockPanel>  
    

    MainWindow.xaml.cs:

    using System;  
    using System.Collections.Generic;  
    using System.Data;  
    using System.IO;  
    using System.Linq;  
    using System.Reflection;  
    using System.Windows;  
    
    namespace DataGridToCVS  
    {  
      public partial class MainWindow : Window  
      {  
        public MainWindow()  
        {  
          InitializeComponent();  
          this.DataContext = this;  
    
    
          this.Products = new List<Product>();  
          for (int i = 0; i < 100; ++i)  
          {  
            Product item = new Product();  
            item.Id = i;  
            item.Name = string.Format("Item {0}", i);  
    
            bool b = (i % 2).Equals(0);  
            item.IsAvailable = b;  
            this.Products.Add(item);  
          }  
        }  
        public IList<Product> Products  
        {  
          get;  
          private set;  
        }  
    
        private void Export_Click(object sender, RoutedEventArgs e)  
        {  
          var filepath = @"C:\Users\...\Desktop\test.csv";  
          // Create the CSV file to which grid data will be exported.  
          StreamWriter sw = new StreamWriter(new FileStream(filepath, FileMode.Create, FileAccess.Write));  
    
          DataSet ds = Products.ConvertToDataSet("table");  
    
          DataTable dt = ds.Tables[0];  
    
          int iColCount = dt.Columns.Count;  
          for (int i = 0; i < iColCount; i++)  
          {  
            sw.Write(dt.Columns[i]);  
            if (i < iColCount - 1)  
            {  
              sw.Write(",");  
            }  
          }  
          sw.Write(sw.NewLine);  
          // Now write all the rows.  
          foreach (DataRow dr in dt.Rows)  
          {  
            for (int i = 0; i < iColCount; i++)  
            {  
              if (!Convert.IsDBNull(dr[i]))  
              {  
                sw.Write(dr[i].ToString());  
              }  
              if (i < iColCount - 1)  
              {  
                sw.Write(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator);  
              }  
            }  
            sw.Write(sw.NewLine);  
          }  
          sw.Close();  
        }  
    
      }  
      public static class C  
      {  
        public static DataSet ConvertToDataSet<T>(this IEnumerable<T> source, string name)  
        {  
          if (source == null)  
            throw new ArgumentNullException("source ");  
          if (string.IsNullOrEmpty(name))  
            throw new ArgumentNullException("name");  
          var converted = new DataSet(name);  
          converted.Tables.Add(NewTable(name, source));  
          return converted;  
        }  
        private static DataTable NewTable<T>(string name, IEnumerable<T> list)  
        {  
          PropertyInfo[] propInfo = typeof(T).GetProperties();  
          DataTable table = Table<T>(name, list, propInfo);  
          IEnumerator<T> enumerator = list.GetEnumerator();  
          while (enumerator.MoveNext())  
            table.Rows.Add(CreateRow<T>(table.NewRow(), enumerator.Current, propInfo));  
          return table;  
        }  
        private static DataRow CreateRow<T>(DataRow row, T listItem, PropertyInfo[] pi)  
        {  
          foreach (PropertyInfo p in pi)  
            row[p.Name.ToString()] = p.GetValue(listItem, null);  
          return row;  
        }  
        private static DataTable Table<T>(string name, IEnumerable<T> list, PropertyInfo[] pi)  
        {  
          DataTable table = new DataTable(name);  
          foreach (PropertyInfo p in pi)  
            table.Columns.Add(p.Name, p.PropertyType);  
          return table;  
        }  
      }  
      public class Product  
      {  
        public int Id { get; set; }  
        public string Name { get; set; }  
        public bool IsAvailable { get; set; }  
      }  
    
    }  
    

    The result:
    201530-image.png

    201576-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.
     Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread. 

    [5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html

    0 comments No comments

0 additional answers

Sort by: Most helpful