簡體   English   中英

如何將 JavaScript 2D 數組復制到剪貼板以將其粘貼到 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 中標記一系列單元格然后將其粘貼回去一樣。

這個解決方案效果驚人。 它使用(類似於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 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);
  });
}

測試:

 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>

編輯:

此解決方案不支持帶有內部換行符或制表符的單元格。 非 ascii unicode 可能會導致某些電子表格程序出現問題。

另請參閱如何在 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>

運行代碼 snipet,點擊按鈕並將粘貼文本復制到 Excel 進行測試。

您必須將數組保存為 JSON 文件,然后才能將 JSON 數據導入到 Excel 工作表中。 按照以下步驟將不同形式的數據導入到 Excel 表格中。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM