如何使用js在浏览器上导出excel
1、首先,界面上要有一个html表格,该表格的内容作为导出用
如
<table border="1" id="dataTable">
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>

2、表格的内容非常简单

3、在js中添加这个函数
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
};
window.location.href = uri + base64(format(template, ctx));
}
})();

4、函数tableToExcel 的第一个参数为table的dom元素或者table的id值,第二个参数是table内容所在的worksheet的名字
比如
tableToExcel(document.getElementById("dataTable"), "导出表格");
5、现在所有内容都准备好了

6、点击运行,成功导出了表格,把它下载下来

7、打开看看,发现内容是正确的
