简体   繁体   中英

How to copy a HTML table with colspan to clipboard in an Excel compatible way?

The copy to clipboard example below demonstrates how one can copy a simple HTML table to the clipboard. Everything works more or less as expected and the table can be inserted into eg Apple Notes, Microsoft Word, ...; All applications respect the colspan and render the table correctly.

An issue arises when pasting this table into Excel. The colspan is simply ignored as shown below:

在此处输入图像描述

Does anyone have an idea how to fix or workaround this issue, such that Excel inserts the table respecting the colspan of the cells?

 const table = document.querySelector('#table'); const copyButton = document.querySelector('#copy'); const pre = document.querySelector('#pre'); copyButton.addEventListener('click', () => { const content = { 'text/html': table.outerHTML }; navigator.clipboard.write([new ClipboardItem(content)]); pre.innerText = JSON.stringify(content); })
 <table id="table" contenteditable="true"> <tr> <td colspan="2">row 0, col 0 - 1</td> <td>row 0, col 2</td> </tr> <tr> <td>row 1, col 0</td> <td>row 1, col 1</td> <td>row 1, col 2</td> </tr> </table> <button id="copy">Copy</button> <br> clipboard content: <pre id="pre" style="overflow:scroll; width:inherit"><pre>

You can preserve the columns and rows by copying the full HTML.

const table = document.querySelector("#mytable")
if (table) {
 const blob = new Blob([table.outerHTML], { type: "text/html" });
  const tableHtml = new ClipboardItem({ "text/html": blob });

  navigator.clipboard.write([tableHtml]).then(function () {
  console.log('Async: Copying to clipboard was successful!');
       }, function (err) {
         console.error('Async: Could not copy text: ', err);
       });
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM