html table转excel

这次分享一个前端的可能大家会用到的,这里也帮别人解决问题时候整理出来的

比较简单,直接上demo吧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
var tableToExcel = (function () {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)))
}
, format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
})
};
return function (table, name) {
if (!table.nodeType) {
table = document.getElementById(table)
}
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML};
document.getElementById("dlink").href = uri + base64(format(template, ctx));
//这里是关键所在,当点击之后,设置a标签的属性,这样就可以更改标签的标题了
document.getElementById("dlink").download = name + '.xls';
document.getElementById("dlink").click();
}
})()
</script>
</head>
<body>


<h1>tableToExcel Demo</h1>
<p>Exporting the W3C Example Table</p>

<a id="dlink" style="display:none;"></a>
<input type="button" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel">

<h4>两行三列:</h4>
<table id='testTable' border="1">
<tr>
<th>姓名</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">电话</th>
<td>555 77 854</td>
</tr>
<tr>
<td>555 77 855</td>
</tr>
</table>

</body>
</html>