<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="exportEx()">导出excel表格</button>
</body>
<script>
var tableData = [{
date: ‘2016-05-02‘,
name: ‘王小虎‘,
address: ‘上海市普陀区金沙江路 1518 弄‘
}, {
date: ‘2016-05-04‘,
name: ‘王小虎‘,
address: ‘上海市普陀区金沙江路 1517 弄‘
}, {
date: ‘2016-05-01‘,
name: ‘王小虎‘,
address: ‘上海市普陀区金沙江路 1519 弄‘
}, {
date: ‘2016-05-03‘,
name: ‘王小虎‘,
address: ‘上海市普陀区金沙江路 1516 弄‘
}]
function exportEx() {
let str = `时间,姓名,地址\n`;
var jsonData = tableData
//增加\t为了不让表格显示科学计数法或者其他格式
for (let i in jsonData) {
for (let j in jsonData[i]) {
str += `${jsonData[i][j] + ‘\t‘},`;
}
str += ‘\n‘;
}
//encodeURIComponent解决中文乱码
let uri = ‘data:text/csv;charset=utf-8,\ufeff‘ + encodeURIComponent(str);
//通过创建a标签
let link = document.createElement("a");
link.href = uri;
link.download = "文件.xls";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
</script>
</html>