在请求中需要设置 responseType: blob
export const requestExport = (api, method, params = {}, config) => {
const apiToken = localStorage.getItem('token');
const data = method === 'GET' ? 'params' : 'data';
let headers = {
'BackServer-Token': `${apiToken}`,
};
if (config?.headers) {
headers = {
...headers,
...config.headers,
};
}
return new Promise((resolve, reject) => {
axios({
...config,
url: baseUrl + api,
method,
[data]: params,
headers,
responseType: 'blob'
})
.then(res => {
if (res.status === 200) {
resolve(res)
}
})
.catch(error => {
ElMessage({
message: '服务器繁忙请稍后重试!',
type: 'error'
})
reject(error);
});
});
};
并且核心在于函数:文章来源:https://www.toymoban.com/news/detail-614768.html
export const download = (fileName, res) => {
const blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
if ("download" in document.createElement("a")) {
const elink = document.createElement("a");
elink.download = fileName;
elink.style.display = "none";
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
}
}
在页面中发送请求:
在 element 的表格组件中对选中的行进行导出文章来源地址https://www.toymoban.com/news/detail-614768.html
const exportTags = async () => {
if (selectId.length < 1) {
ElMessage.error('至少选择一个标签!')
} else {
await exportTag({'tag_ids': selectId}).then(res => {
download('标签列表.xlsx', res)
selectId = []
}, (err) => {
ElMessage.error('导出失败!')
})
}
}
到了这里,关于table 导出表格 Excel的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!