Reputation: 45262
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?
Upvotes: 3
Views: 5489
Reputation: 769
I really recommend using this solution using a hidden textbox:
I've used it to get copy and paste functionality from excel into a datagrid and it works very nicely.
HTH
Upvotes: 2
Reputation: 45262
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.
Upvotes: 2
Reputation: 7341
No, this feature isn't available in SL3.
Please read (Links talk about version 2, but that hasn't changed ever since):
Storing text in the clipboard using Silverlight 2
Upvotes: 2