简体   繁体   English

如何以 Excel 兼容的方式将带有 colspan 的 HTML 表复制到剪贴板?

[英]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.下面的复制到剪贴板示例演示了如何将简单的 HTML 表复制到剪贴板。 Everything works more or less as expected and the table can be inserted into eg Apple Notes, Microsoft Word, ...;一切都或多或少按预期工作,表格可以插入到 Apple Notes、Microsoft Word 等中; All applications respect the colspan and render the table correctly.所有应用程序都尊重 colspan 并正确呈现表格。

An issue arises when pasting this table into Excel.将此表粘贴到 Excel 时出现问题。 The colspan is simply ignored as shown below: colspan 被简单地忽略,如下所示:

在此处输入图像描述

Does anyone have an idea how to fix or workaround this issue, such that Excel inserts the table respecting the colspan of the cells?有谁知道如何修复或解决此问题,例如 Excel 插入尊重单元格跨度的表格?

 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.您可以通过复制完整的 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);
       });
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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