WPF Datagrid – The easy way to export to CSV

Using a data grid in C# / WPF is a pleasure…unless you want to export the data in the grid to a CSV (comma-separated) file (and you don’t know this trick)! What happens is you likely Google something like ‘wpf datagrid export to csv’ and Google provides you with a bunch of results, all articles telling you how to parse through the data-grid, extracting and writing the data from the grid one row, one cell at a time. Now if that’s all you see, it actually starts looks pretty complicated to get the data into a CSV file! Luckily, you are here. 🙂

There is what could reasonably be called a really great shortcut to actually exporting the data out of the WPF data-grid, that doesn’t require looping through, or otherwise manipulating the data-grid in any way.

Copying the data:

The WPF data-grid has the SelectAllCells and UnselectAllCells methods. These methods together with the ApplicationCommands type gives us a way to select all the data, and copy it to the Windows Clipboard. This is just as you would have done if you had selected all the cells of the datagrid with your mouse, and pressed ctrl-c on your keyboard:

datagrid_Results.SelectAllCells();
 
datagrid_Results.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, datagrid_Results);
 
datagrid_Results.UnselectAllCells();

Now the data is copied to the clipboard (notice how this means this method won’t be that great for data files that have gigabytes of data 😉 ) – and that’s it! The scary part is over! You have exported the data from the grid!!! Ok, well, you’ve still only exported it to the Windows Clipboard, so…

Writing the data:

Now you simply need to get the data from the Clipboard, and write it out to a file and you’re done!

string result = (string)System.Windows.Clipboard.GetData(System.Windows.DataFormats.CommaSeparatedValue);
 
File.AppendAllText(fullpath), result, UnicodeEncoding.UTF8);

Check the save location, you should now have your grid data, just as it was in the grid, as a CSV file! Easy.

Happy Coding!