// 导出
exportData () {
this.$confirm('确认导出XXXXXX?', {
confirmButtonText: '导出',
cancelButtonText: '取消',
type: 'question'
}).then(async () => {
try {
let { data ,headers} = await operateReportExport(Params)//请求数据
this.saveExcelFiles(data, 'xxxxx.xls')//从后端请求的数据处理导出Excel文件
//headers请求参数头
//this. handleExportFile(data, headers)//从后端请求的数据处理导出cvs文件
} catch (e) {}
})
}
导出数据处理
//导出excel文件
saveExcelFiles( data, fileName, blobType = "application/vnd.ms-excel") {
if (!data) {
return;
}
let blob = new Blob([data], {
type: blobType
});
downloadFile(blob, fileName);
}
//导出csv
handleExportFile (stream, header, fileType = 'csv') {
let reader = new FileReader()
reader.onload = e => {
try {
let res = JSON.parse(e.target.result)
if (res.msg) {
Message.error(i18n.t(`${res.code}`))
}
} catch (error) {
let disposition = header['content-disposition']
let fileName = disposition ? disposition.match(/filename=(.*)/)[1] : ''
fileName = fileName ? fileName : `${randomRangeId(14)}${+new Date()}.${fileType}`
downloadFile (stream, fileName)
}
}
try {
reader.readAsText(stream)
} catch (error) {
console.log(error)
}
}
//导出实现
downloadFile (stream, fileName, garbledCode = false) {
if ('msSaveOrOpenBlob' in navigator) {
window.navigator.msSaveOrOpenBlob(stream, fileName)
return
}
if (fileName.endsWith('.csv') && garbledCode) stream = '\ufeff' + stream
let url = window.URL.createObjectURL(new Blob([stream]))
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName)
document.body.appendChild(link)
link.click()
link.remove()
}
// 获取num长度的随机id
randomRangeId(num) {
let returnStr = ''
let charStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for (let i = 0; i < num; i++) {
let index = Math.round(Math.random() * (charStr.length - 1))
returnStr += charStr.substring(index, index + 1)
}
return returnStr
}