views:

3304

answers:

3

I'm looking at developing a Silverlight application that displays a lot of information in a DataGrid.

I want to somehow give the users the ability to copy this into Excel via the clipboard.

Is this even possible in Silverlight 3?

+2  A: 

No, this feature isn't available in SL3.

Please read (Links talk about version 2, but that hasn't changed ever since):

Copy text to clipboard?

Storing text in the clipboard using Silverlight 2

Moayad Mardini
+1 for the Blog entry which lead to a hack solution
Andrew Shepherd
+1  A: 

OK, I've figured out how to do it, but it's not exactly elegant.

First of all, I lifted the CopyClipboard function from Jeff Wilcox's Blog.

Now I've written code to generate an HTML table from the grid, and put that into the clipboard.

    private void Clipboard_Button_Clicked(object sender, RoutedEventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<TABLE>");
        foreach (object obj in myDataGrid.ItemsSource)
        {
            sb.Append("<TR>");
            foreach (DataGridColumn c in myDataGrid.Columns)
            {
                sb.Append("<TD>");
                FrameworkElement el = c.GetCellContent(obj);
                TextBlock tb = el as TextBlock;
                if (tb != null)
                {
                    string s = tb.Text;
                    sb.Append(System.Windows.Browser.HttpUtility.HtmlEncode(tb.Text));
                }
                sb.Append("</TD>");
            }
            sb.Append("</TR>");
        }
        sb.Append("</TABLE>");
        Clipboard.SetText(sb.ToString()); 
    }

It's especially bad because it's calling

clipboardData.Invoke("setData", "text", text);

rather than

clipboardData.Invoke("setData", "text/html", text);

Because the second one throws a "System.InvalidOperation" exception. That means if you copy it into Word instead of Excel it isn't a table, it's a block of HTML.

But, yes, copying the datagrid contents to Excel via the clipboard is possible. Sort of.

Andrew Shepherd
The Flash hack is pretty wild, but thanks for linking to it.I hope we add better clipboard support to a future release of Silverlight, it would be useful for advanced grids and other controls.
Jeff Wilcox
+2  A: 

I really recommend using this solution using a hidden textbox:

http://weblogs.asp.net/manishdalal/archive/2008/11/12/cross-browser-copy-and-paste-in-datagrid-with-excel-support-part-1.aspx

I've used it to get copy and paste functionality from excel into a datagrid and it works very nicely.

HTH

Andy Britcliffe