Mat*_*der 5 html javascript excel clipboard
我在网站上创建数据,就像表格一样。我想将该数据复制到excel。我使用 Tabs 转到行中的下一个单元格并使用换行符转到下一行:
let clipboard = 'My link' + "\t" + secondCell + "\t" + thirdCell + "\n" +
firstCellSecondRow + "\t" + secondCellSecondRow + "\t" + thirdCellSecondRow;
navigator.clipboard.writeText(clipboard);
Run Code Online (Sandbox Code Playgroud)
将该文本复制到 Excel 表格中效果很好:
现在我的挑战是,我想添加一个链接到一个单元格的文本。我的直觉方法是将以下文本添加到剪贴板:
let clipboard = '<a href="https://www.my-url.com">My link</a>' + "\t" + secondCell + "\t" + thirdCell + "\n" +
firstCellSecondRow + "\t" + secondCellSecondRow + "\t" + thirdCellSecondRow;
navigator.clipboard.writeText(clipboard);
Run Code Online (Sandbox Code Playgroud)
但这不起作用,它实际上会显示带有 html 的文本:
我想要的只是文本“我的链接”和一个可点击的实际链接:
由于可以在 excel 中复制带有链接的文本,我觉得它应该以某种方式起作用。我可以用 javascript 做到这一点吗?
Twi*_*her 10
以下是在 JavaScript 中实现它的方法:
let html = '<table><tr><td><a href="https://www.my-url.com">My link</a></td><td>secondCell</td></tr><tr><td>firstCellSecondRow</td><td>secondCellSecondRow</td></tr></table>';
const blob = new Blob([html], { type: "text/html" });
navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob })]);
Run Code Online (Sandbox Code Playgroud)
我没有将其写为答案中的片段,因为 StackOverflow 有安全限制,不允许在片段中使用剪贴板。
如果您在控制台中尝试,可能会出现此错误:
未捕获(承诺中)DOMException:文档未聚焦。
这是代码的控制台可测试版本,它意味着您在 3 秒超时期间单击页面:
let html = '<table><tr><td><a href="https://www.my-url.com">My link</a></td><td>secondCell</td></tr><tr><td>firstCellSecondRow</td><td>secondCellSecondRow</td></tr></table>';
const blob = new Blob([html], { type: "text/html" });
setTimeout(() => navigator.clipboard.write([new ClipboardItem({ [blob.type]: blob })]), 3000);
Run Code Online (Sandbox Code Playgroud)
Excel 中的结果:
| 归档时间: |
|
| 查看次数: |
297 次 |
| 最近记录: |