[英]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.