方法一
以下方法为伪excel
<template>
<button @click="exportExcel">导出</button>
//border="1" 为导出的表格添加边框
<table id="table_report" border="1">
<th>
....
</th>
</table>
</template>
export default {
methods:{
exportExcel(){
//window.location.href='<%=basePath%>pmb/excelShowInfo.do';
//获取表格
var exportFileContent = document.getElementById("table_report").outerHTML;
//设置格式为Excel,表格内容通过btoa转化为base64,此方法只在文件较小时使用(小于1M)
//exportFileContent=window.btoa(unescape(encodeURIComponent(exportFileContent)));
//var link = "data:"+MIMEType+";base64," + exportFileContent;
//使用Blob
var blob = new Blob([exportFileContent], {type: "text/plain;charset=utf-8"}); //解决中文乱码问题
blob = new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
//设置链接
var link = window.URL.createObjectURL(blob);
var a = document.createElement("a"); //创建a标签
a.download = "什么什么什么.xls"; //设置被下载的超链接目标(文件名)
a.href = link; //设置a标签的链接
document.body.appendChild(a); //a标签添加到页面
a.click(); //设置a标签触发单击事件
document.body.removeChild(a); //移除a标签
}
}
}
效果图 (实际是html,所以其他为空白)
方法二
<template>
<button @click="exportFile">导出</button>
</template>
export default {
data() {
return{
jsonData:[....], //表格数据
titleList: ['序号', '名称', '时间'], //表格标题
dataField: ['seq', 'name', 'time'], //表格所需要展示的字段
}
},
methods: {
exportFileBtn() {
// 列标题,逗号隔开,每一个逗号就是隔开一个单元格
let str = this.titleList.toString() + '\n';
// 增加\t为了不让表格显示科学计数法或者其他格式
for(let i = 0 ; i < this.jsonData.length ; i++ ){
for(const key of this.dataField){
//此判断为seq后端未返回,所以前端自行添加数据,可根据自己需求删除修改
if(key == 'seq') {
str+=`${i+1 + '\t'},`;
} else {
str+=`${jsonData[i][key]== undefined?'':jsonData[i][key] + '\t'},`;
}
}
str+='\n';
}
// encodeURIComponent解决中文乱码
const uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
// 通过创建a标签实现
const link = document.createElement("a");
link.href = uri;
// 对下载的文件命名
link.download = "json数据表.csv";
link.click();
}
}
}
效果图 (数据字段不同因为文章简单点所以换了,此为本地运行效果)