<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<table id="targetTable">
<tbody>
<tr align="center">
<th>標識</th>
<th>內容</th>
<th>建立時間</th>
</tr>
<tr align="center">
<td>1</td>
<td>excel導出01</td>
<td>2015-07-22</td>
</tr>
<tr align="center">
<td>2</td>
<td>excel導出02</td>
<td>2015-07-22</td>
</tr>
</tbody>
</table>
<a id="exportExcel" href="javascript:;">導出Excel</a>javascript
<script src="https://cdn.bootcss.com/jquery/1.10.1/jquery.js"></script>css
<script>
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><meta http-equiv="Content-type" content="text/html;charset=UTF-8" /><!--[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) {
var ctx = {
worksheet : name || 'Worksheet',
table : table.innerHTML
}
return uri + base64(format(template, ctx));
}
})();
$(function(){
$('#exportExcel').on('click', function(){
var $this = $(this);
//設定下載的文件名及後綴
$this.attr('download', '下載.xls');
//設定下載內容
$this.attr('href', tableToExcel($('#targetTable')[0], '下載'));
});
});
</script>
</body>html
</html>java
須要注意兩點: 1這個方法是不兼容ie的jquery
2若是作下載的時候最後點擊下載的必定是a標籤,就算事件不是加在a標籤上面最終也仍是要動態的建立一個a標籤經過a標籤進行下載app