我需要一种方法来复制 html 表格信息并粘贴到 excel 中。我使用了多种技术组合。首先我添加了这段代码,这样我就可以自动将数据复制到客户端电脑的粘贴缓冲区中。
How do I copy to the clipboard in JavaScript?
// Copies a string to the clipboard. Must be called from within an
// event handler such as click. May return false if it failed, but
// this is not always possible. Browser support for Chrome 43+,
// Firefox 42+, Safari 10+, Edge and IE 10+.
// IE: The clipboard feature may be disabled by an administrator. By
// default a prompt is shown the first time the clipboard is
// used (per session).
function copyToClipboard(text) {
if (window.clipboardData && window.clipboardData.setData) {
// IE specific code path to prevent textarea being shown while dialog is visible.
return clipboardData.setData("Text", text);
} else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge.
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand("copy"); // Security exception may be thrown by some browsers.
} catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return false;
} finally {
document.body.removeChild(textarea);
}
}
}
然后我创建了一个复制字符串。用制表符 \t 分隔单元格值,并用换行符 \n 分隔行。请参阅下面的示例。
我使用 PHP 创建复制数据字符串。
//-- Create data for a single table row
//-- We needed to escape single quotes for HTML and javascript
$copy_data = str_replace("'","\'",$col1."\t".$col2."\t".$col3);
//-- Create data for a multi rows
//-- Separate multiple rows by \n but needs to be escaped so use \\n
$copy_data = str_replace("'","\'",$col1."\t".$col2."\t".$col3."\\n".$col1."\t".$col2."\t".$col3."\\n".$col1."\t".$col2."\t".$col3);
然后我将它放在网页上的复制按钮中。
<a href="#" onclick="copyToClipboard('<?=$copy_data?>')">Copy</a>
然后单击“复制”链接将数据放入复制缓冲区。接下来转到Excel并单击要粘贴数据的单元格,然后进行粘贴。