纯前端excel模板下载与上传校验的实现方式:使用xlsx插件。
我使用的版本为:
"xlsx": "^0.18.5"
一、模板下载
Vue代码示例:
<a-table
id="exportTable"
:columns="exportColumns"
style="width: 100%"
v-show="false"
></a-table>
表格列展示代码为:
const exportColumns = [
{
title: "客户号码",
dataIndex: "customerPhone",
key: "customerPhone",
},
{
title: "是否接通",
dataIndex: "connectInfo",
key: "connectInfo",
},
{
title: "接通后状态",
dataIndex: "communicateInfo",
key: "communicateInfo",
},
{
title: "是否愿意好评",
dataIndex: "appraiseInfo",
key: "appraiseInfo",
},
{
title: "接触日期",
dataIndex: "connectTime",
key: "connectTime",
},
{
title: "客户满意度分池",
dataIndex: "satisfactionLevelInput",
key: "satisfactionLevelInput",
},
];
导入XLSX:
import * as XLSX from "xlsx";
导出代码为:
const download = () => {
let workbook = XLSX.utils.table_to_book(
document.getElementById("exportTable")
); //需要在table上定义一个id
try {
XLSX.writeFile(workbook, "模板.xlsx");
} catch (e) {}
};
二、上传校验
自定义组件importExcel.vue,代码如下:
<template>
<a-upload
v-model:file-list="fileList"
name="file"
:customRequest="importData"
accept=".xls,.xlsx"
class="uploadBtn"
>
<a-button type="primary"> 导入文件 </a-button>
</a-upload>
</template>
<script setup>
import * as XLSX from "xlsx";
const props = defineProps({
oldKey: Array,
newKey: Array,
});
const emit = defineEmits({
finish: null,
});
const importData = (file, fileList) => {
let reader = new FileReader();
/*
reader.readAsBinaryString(file.file) 注意这个是传入的是file.file,
刚开始传的是file、不可以、ant框架是file.file
*/
reader.readAsBinaryString(file.file); //这个是file.file文件,可不是file……
reader.onload = (ev) => {
let res = ev.target.result;
const worker = XLSX.read(res, { type: "binary" });
// 将返回的数据转换为json对象的数据
reader = XLSX.utils.sheet_to_json(worker.Sheets[worker.SheetNames[0]]);
console.log(reader);
emit("finish", transformKey(reader));
};
};
//key转换
const transformKey = (list) => {
let arrNew = [];
list.forEach((item) => {
let obj = {};
props.oldKey.forEach((element, index) => {
obj[props.newKey[index]] = item[element];
});
arrNew.push(obj);
});
return arrNew;
};
</script>
<style scoped>
.uploadBtn {
display: inline-block;
margin-right: 8px;
}
</style>
在页面引用该组件,自定义finish函数对字段进行上传校验和处理:
<ImportExcel :oldKey="oldKey" :newKey="newKey" @finish="finish" />
excel字段转换:
const oldKey = ref([
"客户号码",
"是否接通",
"接通后状态",
"是否愿意好评",
"客户满意度分池",
"接触日期",
]);
const newKey = ref([
"customerPhone",
"connectInfo",
"communicateInfo",
"appraiseInfo",
"satisfactionLevelInput",
"connectTime",
]);