Exporting WPF DataGrid to a text file in a nice looking format. Text file must be easy to read.
- by Andrew
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.