前言,因为项目需求需要,我们需要把后端传来的list转成excel模板,并且下载下来)
之前有用的插件,但是会有少0的情况,如下
所以采用另一个项目用过的方法,最终完美实现效果,如下:
1,首先我们来看下后端提供的数据结构
2,具体前端代码如下
封装的组件,需要的同学直接copy就行(这个方法是在 src - mixins -crud.js文件上写的)
import * as XLSX from 'xlsx'; //直接引入就行
/**
* 导出Excel
* @param json 要导出的json数据
* @param name 要导出的文件名
* @param type 要导出的数据类型
* @constructor
*/
mixinExportJosnToExcel(json, name = 'data', type = 'application/octet-stream') {
let wb = { SheetNames: [], Sheets: {}, Props: { }};
if (!Array.isArray (json)) {
// eslint-disable-next-line no-param-reassign
json = [json];
}
json.forEach (item => {
wb.SheetNames.push (item.sheetName);
wb.Sheets[item.sheetName] = XLSX.utils.json_to_sheet (item.sheetValues, item.sheetOptions);
});
const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };
// eslint-disable-next-line no-use-before-define
let blob = new Blob ([s2ab (XLSX.write (wb, wopts))], { type });
let link = document.createElement ('a');
document.body.appendChild (link);
link.style.display = 'none';
link.href = window.URL.createObjectURL (blob);
link.download = `${name}.xlsx`;
link.click ();
// 释放资源
setTimeout (() => {
URL.revokeObjectURL (link.href);
}, 100);
function s2ab(s) {
if (typeof ArrayBuffer !== 'undefined') {
const buf = new ArrayBuffer (s.length);
const view = new Uint8Array (buf);
for (let i = 0; i !== s.length; ++i) {
view[i] = s.charCodeAt (i) & 0xFF;
}
return buf;
}
const buf = new Array (s.length);
for (let i = 0; i !== s.length; ++i) {
buf[i] = s.charCodeAt (i) & 0xFF;
}
return buf;
}
},
}
}
举例使用:
html
<div class="prompt_three"@click="downloadList()">下载失败结果</div>
现在引入
<script>
import crud from "@/mixins/crud";
export default {
mixins: [crud],
}
</script>
在方法里
//下载失败清单
async downloadList() {
try { //这里的模板数据应是从上传之后的确定按钮拿到的
let arr = []
let telephone=''
this.errorList.forEach(one=>{ //this.errorList就是拿到的后端list
if(one.serviceConsultantList && one.serviceConsultantList.length>0){
one.serviceConsultantList.forEach((two,index) => {
console.log(index+1 , one.serviceConsultantList.length)
telephone += `${two.telephone}${index+1 == one.serviceConsultantList.length ? '' : '、'}`
})
}else{
telephone=''
}
arr.push({
'酒店code': one.hotelId,
'服务顾问姓名':one.nameList && one.nameList.length>0?one.nameList.join("、"):null,
'服务顾问联系方式': telephone,
'失败原因': one.errorReason,
})
})
const json = {
sheetName: '酒店导入失败明细',
sheetValues: arr
};
this.mixinExportJosnToExcel (json,'批量导入员工失败清单');
} catch (error) {
console.log(error,"error")
}
},
ok,已完