一、导出效果
二、导出代码
download() {
let data = [{
name: 'aaaa',
age: 10,
address: '广东',
phone: '1',
wechart: '1'
},
{
name: 'bbbb',
age: 11,
address: '广西',
phone: '2',
wechart: '2'
},
{
name: 'cccc',
age: 12,
address: '山东',
phone: '3',
wechart: '3'
}
]
if (!data.length) {
this.$Message.warning('没有可以导出的数据');
return;
}
let table = `<table border="1px" cellspacing="0" cellpadding="0">
<thead>
<th>序号</th>
<th>姓名</th>
<th>年龄</th>
<th>地址</th>
<th>手机号</th>
<th>微信号</th>
</thead>
<tbody>
`;
for (let i = 0; i < data.length; i++) {
let {
name,
age,
address,
phone,
wechart
} = data[i];
table += `<tr>
<td>${i + 1}</td>
<td>${name} </td>
<td>${age}</td>
<td>${address}</td>
<td>${phone}</td>
<td>${wechart}</td>
</tr>`;
}
table += '</tbody>';
table += '</table>';
let html = `<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'>
<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
<head>
</head>
<body>
${table}
</body>
</html>`;
let url = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(html);
let a = document.createElement('a');
a.href = url;
a.download = `${new Date().Format('yyyyMMddhhmmss')}.xls`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}