views:

29

answers:

2

Hi, Is there a simple way to export a WPF DataGrid to a text file and a .csv file? I've done some searching and can't see that there is a simple DataGrid method to do so. I have got something working (barely) by making use of the ItemsSource of the DataGrid. In my case, this is an array of structs. I do something with StreamWriters and StringBuilders (details available) and basically have:

StringBuilder destination = new StringBuilder();
destination.Append(row.CreationDate);
destination.Append(seperator);  // seperator is '\t' or ',' for csv file
destination.Append(row.ProcId);
destination.Append(seperator);
destination.Append(row.PartNumber);
destination.Append(seperator);

I do this for each struct in the array (in a loop). This works fine. The problem is that it's not easy to read the text file. The data can be of different lengths within the same column. I'd like to see something like: 2007-03-03 234238423823 823829923 2007-03-03 66 99 And of course, I get something like: 2007-03-03 234238423823 823829923 2007-03-03 66 99

It's not surprising giving that I'm using Tab delimiters, but I hope to do better. It certainly is easy to read in the DataGrid! I could of course have some logic to pad short values with spaces, but that seems quite messy. I thought there might be a better way. I also have a feeling that this is a common problem and one that has probably been solved before (hopefully within the .NET classes themselves).

Thanks.

A: 

I assume the goal is to be as WYSIWYG as possible. In that case I would:

  1. Loop through all DataGridRows, and for each one build a string[] containing the data displayed in each DataGridCell. This is easy for most DataGridColumn types. For DataGridTemplateColumn you'll need to use the Binding then convert .ToString().
  2. I also would keep track of the maximum string length in each column as I did so.

The next step depends on the export type:

  • For a csv export I would then append all the strings in each string[] inside quotes with commas between them and write them out.
  • For a plain text export I would append all the strings in each string[] padded with spaces to 1+ the maximum string length for that column and write them out.

The reason to use the actual DataGridRow, DataGridCell and DataGridColumn objects is to write out exactly what the end-user sees. For example you can skip hidden columns, apply string formats in binding, honor filtering/grouping/sorting, etc.

Ray Burns
A: 

I would use the Application.Copy functionality of the grid, select all then copy in code, then you can parse the clipboard helper data which is in csv, html and a few other formats.

Aran Mulholland