0

How would you copy multiple rows of data like this <tr><td>cell 1</td><td>cell 2</td></tr> <tr><td>cell 3</td></td>cell 4</td></tr> into user's clipboard, ready to be pasted in Excel (one <td> pair will go to one cell in Excel)

I have something like this in mind:

$('#copy').click(function(){
   var data = $('datatable tr:visible').text();
   alert("you have copied these data: " + data + "now you can paste them in Excel");
});

Nothing in data variable in the alert box. Pretty much stuck here..

user666923
  • 87
  • 3
  • 14

1 Answers1

2

If you want to paste the data in Excel, you'll probably need each row in a different line, each column separated by tabs. Example:

var rows = []
$('datatable tr:visible').each(function() {
    var columns = [];
    $(this).children("td").each(function() {
        columns.push($(this).text());
    });
    rows.push(columns.join("\t");
});
var data = rows.join("\n");

Working example at jsFiddle (adapted from OP code)

As for copying to clipboad, see this question for more info.

Update: Copying from browser to clipboard is a complicated and potentially insecure operation, and AFAIK does not work consistently between browsers and operating systems. Maybe it's better to just drop the text in a textarea, selected, and request the user to Ctrl+C it. But it's up to you.

Community
  • 1
  • 1
mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
  • It's my first time using this fiddle: [link]http://jsfiddle.net/DXjft/2/ there is nothing happening.. – user666923 Mar 10 '12 at 20:31
  • 1. There's no `datatable`, just `table` (*Edit:* in the 1st fiddle, I see you fixed it in the 2nd); 2. Don't use `tr > td`, you're iterating over rows in the outer loop; 3. There's no `#testing`, and `append` is used with html, not text; 4. I believe `clipboardData` only works in IE. See [this](http://jsfiddle.net/mgibsonbr/DXjft/5/) for a closer-to-working example. – mgibsonbr Mar 10 '12 at 20:39
  • Thank you so much mgibsonbr! I corrected the silly mistake you spotted and you code rocks! I use this method for clipboard:`window.clipboardData.setData('Text',str);` I only need to make it work in IE in my situation. Thanks! – user666923 Mar 10 '12 at 20:46