- 之前写过文件流导出excel,这次直接把上次的代码拿过来复制粘贴,但是导出的表格里面没有数据,只显示undefined。
- 这是之前的代码
export function exportList(query) {
return request({
url: '/api/xxx/xxx',
method: 'get',
params: query,
responseType:'blob'
})
}
methods: {
exportExcel() {
exportList()
.then(res => {
let data = res.data;
if (!data) {
return;
}
let url = window.URL.createObjectURL(new Blob([data]));
let a = document.createElement("a");
a.style.display = "none";
a.href = url;
a.setAttribute("download", "excel.xls");
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
})
.catch(error => {
console.log(error);
});
}
}
- 后来打印发现了问题
- 上图是打印的结果,发现是blob的size不一样
- 解决办法,里面添加'charset=utf-8'
- 上代码
exportExcel() {
exportList()
.then((res) => {
var content = res;
var data = new Blob([content],{type:"application/vnd.ms-excel;charset=utf-8"});
var downloadUrl = window.URL.createObjectURL(data);
var a = document.createElement("a");
a.href = downloadUrl;
a.setAttribute("download", "excel.xls");
a.click();
window.URL.revokeObjectURL(data);
})
.catch((error) => {
console.log(error);
});
},
- 其实我还在 exportList()里面传了参数,为了能简单易懂,传参部分就删掉了-