js将表格通过剪贴板复制到excel和word
发布日期:2024-08-20 07:26:58
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table{
border-collapse: collapse;
}
th,td {
border:1px solid #000;
}
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>
<body>
<table id="table1">
<thead>
<tr>
<th colspan="2" rowspan="2">标题1</th>
<th colspan="2">标题2</th>
<th rowspan="3">标题3</th>
</tr>
<tr>
<th>标题21</th>
<th>标题22</th>
</tr>
<tr>
<th>标题31</th>
<th>标题32</th>
<th>标题31</th>
<th>标题32</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="3">01</td>
<td rowspan="2">02</td>
<td>03</td>
<td>04</td>
<td>05</td>
</tr>
<tr>
<td>13</td>
<td>24</td>
<td>35</td>
</tr>
<tr>
<td >22</td>
<td>63</td>
<td>54</td>
<td>25</td>
</tr>
<tr>
<td colspan="2">22</td>
<td>63</td>
<td>54</td>
<td>25</td>
</tr>
</tbody>
</table>
<br />
<input type="button" onclick="copy()" value="拷贝到剪贴板" />
</body>
</html>
<script>
$(function () {
});
function copy(text) {
console.log('开始复制');
console.log($("table").get(0))
const range = document.createRange();
range.selectNode($("table").get(0));
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
let result = false;
result = document.execCommand('copy');
console.log(result)
console.log('选中内容已复制到系统粘贴板');
alert("已复制到剪贴板!")
}
</script>