WPF Data grid to CSV and HTML the easy way
Written by Mike James   
Thursday, 11 November 2010
Article Index
WPF Data grid to CSV and HTML the easy way
Using the clipboard

Banner

The DataGrid to Clipboard

Our first task is to copy all of the data displayed in the grid to the Clipboard. The first task is to select all of the cells ready for copying:

dataGrid1.SelectAllCells();

next we need to set the copy mode to determine if we need the headings:

dataGrid1.ClipboardCopyMode = 
DataGridClipboardCopyMode.IncludeHeader;

You can just as well select ExcludeHeader if you don't want the first CSV record to include the headers. Some applications make use of the headers when importing data, some don't.

To copy the data to the clipboard is a very complicated operation if you worry about how it all works. The Clipboard object has methods that let you transfer data and these are easy to use. However, in WPF there is a system of standard commands that UI objects can choose to implement. One of these standard commands is Copy and in most cases it is interpreted as a request for a UI object to copy its data to the clipboard.

The idea is that you set up a menu item that issues the Copy command and the currently selected UI object receives it and implements the copy to clipboard. This system allows a single command to be received and interpreted by a range of UI objects - and clearly this is simpler than having to hookup copy commands to each UI object in turn.

As well as allowing the user to trigger a command the system also allows the command to be raised in code - although how to do this is well hidden in the documentation. The DataGrid has an implementation of the Copy command which transfers all of the data in the currently selected cells to the Clipboard in three formats - CSV, text and HTML. The HTML takes the form of a table.

The method that does the copy to the Clipboard object is OnExecuteCopy this is an event handler and WPF commands are implemented as events. You can't simply call the OnExecuteCopy event handler, however, because it is protected. You can access it in a roundabout and complicated way but why bother when there is an easier route? The ApplicationsCommands object maintains list of standard commands as properties and can retrieve the Routed UICommand object that represents the command and this can be used to raise the appropriate event on an object of your choice.

So to invoke the OnExecuteCopy eventhander on the DataGrid instance you simply have to write:

ApplicationCommands.Copy.Execute(
null, dataGrid1);

Other commands can be executed in the same way. The first parameter is an optional object which is passed to the eventhandler to provide it with parameters. In the case of Copy no parameters are needed.

Now we have all of the data in the grid copied to the ClipBoard object in three formats - time to unselect the cells to restore the grid to its original state:

dataGrid1.UnselectAllCells();

The Clipboard to a File

Now we have the data on the Clipboard and at this point one way to proceed would be manually, i.e. load Excel say and use the Paste command to transfer the data. To do the same job automatically is just as easy, however.

First we retrieve the data on the Clipboard into an Object and cast it to a string:

String result=(string)Clipboard.GetData(
DataFormats.CommaSeparatedValue);

Notice that the DataFormats doesn't do any conversion to the specified format. GetData retrieves the data in the specified format if it exists on the Clipboard.

Now we have the data in the string we can clear the Clipboard:

Clipboard.Clear();

and write the data out ot a file:

 

System.IO.StreamWriter file = 
new System.IO.StreamWriter("c:\\test.csv");
file.WriteLine(result);
file.Close();

Where of course you can set the filename to anything you want.  That's all there is to it - now we have a CSV file ready to use.

excel

If you want an HTML file simply change the instruction that gets the data from the Clipboard to:

String result=(string)Clipboard.GetData(
DataFormats.Html);

The HTML is  little more tricky to use in that it contains a header which indicates where the different portions of the HTML start and stop. You can use this header to extract either an entire web page or just the table to use in another page.

Conclusion

Sometimes things are too easy and you just have to think about how much time you could have wasted if you missed how to use the WPF command framework. You can use similar techniques to execute standard commands on other UI controls.

Look out for a future article on how the WPF commands work and on how to implement your own.

If you would like to be informed about new articles on I Programmer you can either follow us on Twitter, on Facebook , on Digg or you can subscribe to our weekly newsletter.

<ASIN:1430219106>

<ASIN:0672331195>

<ASIN:1430272058>


Banner


Analytics As A Service

If you think that Google Analytics is the last word in finding out how your web site is being used then you need to think again. There may well be a better option.



Monitor Mobile

Monitoring mobile apps should be easy, all you need to do is arrange to send the data back to a server - but what server? There is enough to do without having to implement a complete monitoring system [ ... ]


Other Projects



Last Updated ( Thursday, 11 November 2010 )
 
 

   
RSS feed of all content
I Programmer - full contents
Copyright © 2014 i-programmer.info. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License.