js处理下载的问题
<!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>
<script src="https://cdn.bootcss.com/jquery/1.10.1/jquery.js"></script>
<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>
需要注意两点: 1这个方法是不兼容ie的
2如果做下载的时候最后点击下载的一定是a标签,就算事件不是加在a标签上面最终也还是要动态的创建一个a标签通过a标签进行下载