Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a JavaScript 2D array to clipboard to paste it in excel?

Example 2D array:

var arr = [
  ["Mike", "Cane", 23],
  ["Jeff", "Meyers", 46],
  ["Thomas", "Bush", 67]
]

How do I copy a 2D array to the clipboard to then paste it in an excel spreadsheet? The rows and columns should be preserved as it is in the array. It should work the same way as if I would mark a range of cells in excel and then paste it back in.

like image 626
oemera Avatar asked Mar 15 '20 22:03

oemera


People also ask

How do you paste data into Excel?

Select the cells that contain the data or other attributes that you want to copy. Click the first cell in the area where you want to paste what you copied. On the Home tab, under Edit, click Paste, and then click Paste Special. Paste all cell contents and formatting, including linked data.

How do I copy and paste data from one column to another?

Move or copy just the contents of a cell Select the row or column that you want to move or copy. In the cell, click where you want to paste the characters, or double-click another cell to move or copy the data. or press Ctrl+V. Press ENTER.

How do you paste with rows?

After you copy a cell or row, right-click the destination cell. Select Paste Special. Choose how you want to paste the cell or row content.


2 Answers

This solution works amazing. It uses (CSV like) line breaks for a new row and tab for a new cell. Pasting text like this in an Excel, OpenOffice / LibreOffice Calc spreadsheet, it will detect it as multiple cells. It also works with Google Docs.

function copy2DToClipboard(array) {
  var csv = '', row, cell;
  for (row = 0; row < array.length; row++) {
    for (cell = 0; cell < array[row].length; cell++) {
      csv += (array[row][cell]+'').replace(/[\n\t]+/g, ' ');
      if (cell+1 < array[row].length) csv += '\t';
    }
    if (row+1 < array.length) csv += '\n';
  }
  copyTextToClipboard(csv);
}

// copied from https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript
function fallbackCopyTextToClipboard(text) {
  var textArea = document.createElement("textarea");
  textArea.value = text;

  // Avoid scrolling to bottom
  textArea.style.top = "0";
  textArea.style.left = "0";
  textArea.style.position = "fixed";

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    // console.log('Fallback: Copying text command was ' + msg);
  } catch (err) {
    console.error('Fallback: Oops, unable to copy', err);
  }

  document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
  if (!navigator.clipboard) {
    fallbackCopyTextToClipboard(text);
    return;
  }
  navigator.clipboard.writeText(text).then(function() {
    // console.log('Async: Copying to clipboard was successful!');
  }, function(err) {
    console.error('Async: Could not copy text: ', err);
  });
}

Test:

function onTest() {
  const arr = [
    ["Mike", "Cane", 23],
    ["Jeff", "Meyers", 46],
    ["Thomas", "Bush", 67]
  ];
  copy2DToClipboard(arr);
  document.getElementById('test').innerText = 'Copied!';
}

function copy2DToClipboard(array) {
  var csv = '', row, cell;
  for (row = 0; row < array.length; row++) {
    for (cell = 0; cell < array[row].length; cell++) {
      csv += (array[row][cell]+'').replace(/[\n\t]+/g, ' ');
      if (cell+1 < array[row].length) csv += '\t';
    }
    if (row+1 < array.length) csv += '\n';
  }
  copyTextToClipboard(csv);
}

// copied from https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript
function fallbackCopyTextToClipboard(text) {
  var textArea = document.createElement("textarea");
  textArea.value = text;
  
  // Avoid scrolling to bottom
  textArea.style.top = "0";
  textArea.style.left = "0";
  textArea.style.position = "fixed";

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    // console.log('Fallback: Copying text command was ' + msg);
  } catch (err) {
    console.error('Fallback: Oops, unable to copy', err);
  }

  document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
  if (!navigator.clipboard) {
    fallbackCopyTextToClipboard(text);
    return;
  }
  navigator.clipboard.writeText(text).then(function() {
    // console.log('Async: Copying to clipboard was successful!');
  }, function(err) {
    console.error('Async: Could not copy text: ', err);
  });
}
<button onclick="onTest()" id="test">Copy to clipboard.</button>

Edit:

This solution does not support cells with internal line breaks or tabs. Non-ascii unicodes can cause problems with some spreadsheet programs.

See also How do I copy to the clipboard in JavaScript?

like image 125
Niklas E. Avatar answered Oct 26 '22 13:10

Niklas E.


It's pretty easy, you just have to add a tab character \t to separate columns and a new line \n to seperate rows.

Use this code:

const excelData = arr
  .map(lines => lines.join("\t"))
  .join("\n");

const arr = [
  ["Mike", "Cane", 23],
  ["Jeff", "Meyers", 46],
  ["Thomas", "Bush", 67]
];

document.getElementById('convert').addEventListener('click', () => {
  const excelData = arr
    .map(lines => lines.join("\t"))
    .join("\n");
 
  document.getElementById('excel').textContent = excelData;
});
<textarea id="excel" cols="30" rows="6"></textarea><br>
<button id="convert">Make Excel Clipboard data</button>

Run code snipet, hit the button and copy paste text to Excel to test it out.

like image 33
Christos Lytras Avatar answered Oct 26 '22 12:10

Christos Lytras