1.平時(shí)前端導(dǎo)出excel表格時(shí)簡(jiǎn)單的方式
window.location.href="后臺(tái)接口地址"嗅榕;
2.有時(shí)候?qū)С鲂枰獧?quán)限的時(shí)候澡匪,后臺(tái)要求在導(dǎo)出的時(shí)候要在headers里面加token蒂秘;這是第一種方式就不行了减江,一般我們會(huì)通過(guò)ajax染突,或者axios,或者其他的請(qǐng)求方式獲取后臺(tái)數(shù)據(jù)的時(shí)候統(tǒng)一處理headers里面的token辈灼;
具體代碼,拿到后臺(tái)返回的數(shù)據(jù)后
const blob = new Blob([res], { // res 為后臺(tái)返回?cái)?shù)據(jù)
type: 'application/vnd.ms-excel;charset=utf-8', // 導(dǎo)出數(shù)據(jù)生成excel的格式設(shè)置
});
if ('download' in document.createElement('a')) {
// 非IE下載
const elink = document.createElement('a');
elink.download = `${fileName}.xls`;
elink.style.display = 'none';
elink.target = '_blank';
elink.href = window.URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
}
3.還有一點(diǎn)需要注意份企,在獲取到后臺(tái)數(shù)據(jù)的時(shí)候,我們要設(shè)置一些接收后臺(tái)數(shù)據(jù)類型格式
{
responseType: 'blob',
}