一海蔽、后臺返回文檔流
export().then(res => {
const content = res
const blob = new Blob([content])
const fileName = '導(dǎo)出信息.xlsx'
if ('download' in document.createElement('a')) { // 非IE下載
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)
} else { // IE10+下載
navigator.msSaveBlob(blob, fileName)
}
})
}
//防止亂碼在請求方法中添加返回數(shù)據(jù)類型
responseType: 'arraybuffer'
二、后臺返回json數(shù)據(jù)
exprotExcel() {
//要導(dǎo)出的json數(shù)據(jù)
var jsonData = [
{
name:'路人甲',
phone:'123456',
email:'123@123456.com'
},
{
name:'炮灰乙',
phone:'123456',
email:'123@123456.com'
},
{
name:'土匪丙',
phone:'123456',
email:'123@123456.com'
},
{
name:'流氓丁',
phone:'123456',
email:'123@123456.com'
},]
//列標(biāo)題笤休,逗號隔開救崔,每一個逗號就是隔開一個單元格
let str = `姓名,電話,郵箱\n`;
//增加\t為了不讓表格顯示科學(xué)計數(shù)法或者其他格式
for(let i = 0 ; i < jsonData.length ; i++ ){
for(let item in jsonData[i]){
let jsonStr = jsonData[i][item] + ''
// 為了防止字符串中存在英文的“锭部,”所以要替換一下
str+=`${jsonStr.replace(/,/g, ",")+ '\t'},`;
}
str+='\n';
}
//encodeURIComponent解決中文亂碼
let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
//通過創(chuàng)建a標(biāo)簽實現(xiàn)
var link = document.createElement("a");
link.href = uri;
//對下載的文件命名
link.download = "json數(shù)據(jù)表.csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}