question

Serhatzyldz-5606 avatar image
0 Votes"
Serhatzyldz-5606 asked HuiLiu-MSFT answered

Export datagrid to .csv in WPF

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-wpf
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

HuiLiu-MSFT avatar image
0 Votes"
HuiLiu-MSFT answered

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 to enable e-mail notifications if you want to receive the related email notification for this thread. 


image.png (21.0 KiB)
image.png (44.6 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.