由于一些网络通讯协议的限制,你必须使用 window.btoa() 方法对原数据进行编码后,才能进行发送。接收方使用相当于 window.atob() 的方法对接受到的 base64 数据进行解码,得到原数据。例如,发送某些含有 ASCII 码表中 0 到 31 之间的控制字符的数据。
所以需要配合
encodeURIComponent 和 decodeURIComponent
encodeURI 和 decodeURI
encodeURI()和encodeURIComponent() 区别
https://blog.csdn.net/qq_34629352/article/details/78959707
js代码如下:
<script type="text/javascript">var tableToExcel = (function () {
var uri = 'data:application/vnd.ms-excelbase64,'
, 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}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
调用方法如下:
<table id="test"><tr>
<td>test</td><td>test</td>
</tr>
<tr>
<td>test</td><td>test</td>
</tr>
<tr>
<td>test</td><td>test</td>
</tr>
<tr>
<td>test</td><td>test</td>
</tr>
<tr>
<td>test</td><td>test</td>
</tr>
</table>
<button class="" onclick="tableToExcel('test')">导出指定ID的表格到EXCEL</button>
用法说明:
tableToExcel方法传入要导出table的id