[英]Copy hyperlink text and plain text to the clipboard, then paste them into Excel using Javascript/JQuery in multiple cells of a row?
我的目标是制作一个 function,在特定页面上收集数据并将其复制到剪贴板,然后粘贴到 Google 表格或 Excel 电子表格中。
数据出现在网页的不同位置,呈现如下:
<!-- Somewhere throughout the web page -->
<div data-cy="a">
<strong><a href="www.example.com">text</a></strong>
</div>
<!-- Another place throughout the web page -->
<div data-cy="b">
<strong>another text</strong>
</div>
此外,我需要推送一些简单的字符串,例如var text = 'different text'
。
在 Excel 电子表格中,应将三个值粘贴到一行中的三个匹配字段中:
一种 | 乙 | C | |
---|---|---|---|
1个 | 文本 | 另一个文本 | 不同的文字 |
到目前为止,这是我的代码:
var a = $('*[data-cy="a"]').html().replaceAll('\n','').replaceAll('<strong>','').replaceAll('</strong>','') // extract 'a'.
var b = $('*[data-cy="b"]').html().replaceAll('\n','').split(/[><]/)[2]; // extract 'b'.
var c = 'different text';
var allCells = a + '\t' + b + '\t' + c; // using Tab character to divide between cells.
function copyToClipboard(str) {
function listener(e) {
e.clipboardData.setData("text/html", str);
e.clipboardData.setData("text/plain", str);
e.preventDefault();
}
document.addEventListener("copy", listener);
document.execCommand("copy");
document.removeEventListener("copy", listener);
};
copyToClipboard(allCells);
我尝试了navigator.clipboard.writeText()
的已弃用版本和更新版本,但这些似乎都没有让我选择将值粘贴到同一行的不同单元格中。
这个评论帮助我弄清楚实际发生了什么。 不幸的是,为了解决这个问题,我在 DOM 中创建了一个新表并从那里复制了元素。 粘贴到 Excel 工作表就像一个魅力。
// Extraction of variables
var a = $('*[data-cy="a"]').html().replaceAll('\n','').replaceAll('<strong>','').replaceAll('</strong>','') // extract 'a'.
var b = $('*[data-cy="b"]').html().replaceAll('\n','').split(/[><]/)[2]; // extract 'b'.
var c = 'different text';
let allCells = [$(clientName), locationCompany, treatedBy];
// Table creation
var table = $('<table>').addClass('table').attr('id', 'excel-data');
var row = $('<tr>');
for(i=0; i<allCells.length; i++) {
row.append($('<td>').html(allCells[i]));
}
table.append(row);
$('[data="element-data"]').append(table);
// Select & copy table function
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
document.execCommand("copy");
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
range.execCommand("Copy");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.