npm install xlsx
详细实现请见如下案例
<template>
<div class='file'>
<button class='file-btn' type='default' @click='fileXlsx'>上传JC Number 获取Approvers</button>
<p>{{ fileName }}</p>
<input class='uploadFile' type='file' @change='fileChange'>
</div>
</template>
<script>
import { read, utils, writeFile } from 'xlsx';
import { getCandidateInfoByJCNumber } from '../../../api';
export default {
name: 'FileXlsxGetApprovalers',
data() {
return {
fileName: ''
};
},
methods: {
fileXlsx() {
document.querySelector('.uploadFile').click();
},
fileChange(event) {
if (!event.currentTarget.files.length) {
return false;
}
// 拿取文件对象
const file = event.target.files[0];
// 显示文件名
this.fileName = file.name;
// 用FileReader来读取
const reader = new FileReader();
// 重写FileReader上的readAsBinaryString方法
const rABS = true;
reader.onload = (e) => {
let dataResult = e.target.result;
if (!rABS) dataResult = new Uint8Array(dataResult);
const workbook = read(dataResult, {
type: rABS ? 'binary' : 'array'
});
// 假设我们的数据在第一个标签
const firstWorksheet = workbook.Sheets[workbook.SheetNames[0]];
// XLSX自带了一个工具把导入的数据转成json
const jsonArr = utils.sheet_to_json(firstWorksheet, { header: 1 });
document.querySelector('.uploadFile').value = null;
const data = jsonArr.map(item => item[0]);
this.getJCNumberData(data);
};
if (rABS) reader.readAsBinaryString(file);
else reader.readAsArrayBuffer(file);
return false;
},
getJCNumberData(paramsArr) {
const arr = [];
paramsArr.forEach(item => {
arr.push(getCandidateInfoByJCNumber({ id: item }));
});
// 将返回数据写入xlsx并下载
// eslint-disable-next-line compat/compat
Promise.all(arr).then(res => {
//res=[{name:'张三',age:18}]
const ws=utils.json_to_sheet(res);
const wb=utils.book_new();
utils.book_append_sheet(wb,ws,'Approvers');
writeFile(wb, "Approvers.xlsx");
});
}
}
};
</script>
<style lang='less' scoped>
.file {
padding-top: 30px;
}
.uploadFile {
display: none;
}
</style>
网友评论