使用原生js导出,不需要插件
动手试过,确实可行
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick='tableToExcel()'>导出</button>
<script>
const tableToExcel = () => {
// 要导出的json数据
const jsonData = [
{
name:'张三',
phone:'123456',
email:'1111111'
},
{
name:'李四',
phone:'123456',
email:'2222222'
},
{
name:'王五',
phone:'123456',
email:'3333333'
},
{
name:'赵六',
phone:'123456',
email:'4444444'
},
]
// 列标题 ----和数据顺序对应
let str = '<tr><td>姓名</td><td>电话</td><td>邮箱</td></tr>';
// 循环遍历,每行加入tr标签,每个单元格加td标签
for(let i = 0 ; i < jsonData.length ; i++ ){
str+='<tr>';
for(const key in jsonData[i]){
// 增加\t为了不让表格显示科学计数法或者其他格式
str+=`<td>${ jsonData[i][key] + '\t'}</td>`;
}
str+='</tr>';
}
const fileName = this.selectData.title || '下载';
const worksheet = this.selectData.title || 'Sheet1';//sheet名字
const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
const style = `
td:{text-align:center}
`;
// 下载的表格模板数据
const 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]-->
<style>${style}</style>
</head><body><table border="1" cellspacing="0" cellpadding="0">${str}</table></body></html>`;
const url = 'data:application/vnd.ms-excel;base64,' + base64(template);
// 下载模板
const a = document.createElement('a');
a.download = `${fileName}.xls`;
a.href = url;
a.click();
};
</script>
</body>
</html>
unescape 已被废弃,可尝试下面的方法
// 创建blob
let blob = new Blob([html], { type: "application/msword;charset=UTF-8" });
// 创建链接
let url = URL.createObjectURL(blob);
let link = document.createElement("a");
link.href = url;
link.download = exportWordObj.exportName ? exportWordObj.exportName : "文档.doc";
document.body.appendChild(link);
// 下载文件
link.click();
// 清理
document.body.removeChild(link);
URL.revokeObjectURL(url);