1.首先安装依赖
import XLSX from "xlsx";
2.建立读取excel文件的js文件,以便调用
// importExcel.js
import XLSX from 'xlsx';
export function readExcel(file) {
return new Promise((resolve, reject) => {
const types = file.name.split(".")[1];
const fileType = [
"xlsx",
"xlc",
"xlm",
"xls",
"xlt",
"xlw",
"csv",
].some((item) => item == types);
if (!fileType) {
return reject({ message: "格式错误!请重新选择" });
}
const reader = new FileReader();
const result = [];
reader.onload = function (e) {
const data = e.target.result;
const wb = XLSX.read(data, {
type: "binary",
});
wb.SheetNames.forEach((sheetName) => {
result.push({
sheetName: sheetName,
sheet: XLSX.utils.sheet_to_json(wb.Sheets[sheetName]),
});
resolve(result.length > 1 ? result : result[0].sheet);
});
};
reader.onerror = function (error) {
return reject(error);
};
reader.readAsBinaryString(file.raw || file);
});
}
export function formatJson(header, filterVal, jsonData) {
return jsonData.map((v) => {
const obj = {};
header.forEach((h, i) => {
obj[[`${filterVal[i]}`]] = v[h];
});
return obj;
});
}
3、然后在引入element-ui后,使用upload组件实现上传按钮
<el-upload
class="upload-draw-log"
ref="upload"
action=""
accept=".xlsx, .xls"
:show-file-list="false"
:http-request="uploadDrawLog"
:on-change="onChange"
:limit="1"
>
<el-button class="btn" type="primary"> 上传中奖名单 </el-button>
</el-upload>
4、创建upload按钮调用的方法
async uploadDrawLog(e) {
try {
this.isLoading = true;
const data = await readExcel(e.file);
const header = [
"会员id",
"会员昵称",
"素材id",
"评论id",
"充值卡密码",
"期数",
];
const filterVal = [
"customerId",
"nickName",
"composeId",
"commentId",
"passwordCard",
"periods",
];
const _data = formatJson(header, filterVal, data);
await WinningApi.uploadDrawLog(_data);
this.isLoading = false;
} catch (error) {
console.error(error);
this.isLoading = false;
this.$message.error(error.message || error);
}
this.$refs.upload.clearFiles();
},
onChange(file, fileList) {
console.log({ file, fileList });
},
参考文献:https://blog.csdn.net/weixin_42864357/article/details/104295187