如何将 JavaScript 二维数组复制到剪贴板以将其粘贴到 excel 中?

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

示例二维数组:

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

如何将二维数组复制到剪贴板,然后将其粘贴到 excel 电子表格中? 行和列应保留在数组中。 它的工作方式应该与我在 excel 中标记一系列单元格然后将其粘贴回去的方式相同。

您必须将数组保存为 JSON 文件,然后您可以将 JSON 数据导入 excel sheet。按照以下步骤将不同形式的数据导入到 excel sheet.

https://support.office.com/en-us/article/import-data-from-external-data-sources-power-query-be4330b3-5356-486c-a168-b68e9e616f5a

这个解决方案效果惊人。它对新行使用(CSV 类似)换行符,对新单元格使用制表符。在 Excel、OpenOffice / LibreOffice Calc 电子表格中粘贴这样的文本,它会将其检测为多个单元格。它还适用于 Google 文档。

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 
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);
  });
}

测试:

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 
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>

编辑:

此解决方案不支持带有内部换行符或制表符的单元格。非 ASCII Unicode 可能会导致某些电子表格程序出现问题。

另见 How do I copy to the clipboard in JavaScript?

这很简单,您只需添加一个制表符 \t 来分隔列和一个新行 \n 来分隔行。

使用此代码:

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>

运行 代码片段,点击按钮并将粘贴文本复制到 Excel 进行测试。