上传组件
<el-upload
v-model:file-list="subFileList"
action="#"
accept=".xls, .xlsx"
ref="coverUploadExcel"
:on-exceed="handleExceed"
:on-change="handleChange"
:multiple="false"
:http-request="(file: any) => { return state.import.uploadHandle(file) }"
>
<el-button type="primary">选择文件</el-button>
</el-upload>
插件使用的是:xlsx
import * as XLSX from "xlsx";
const upload = ref<UploadInstance>();
// 上传前的操作
const handleExceed: UploadProps["onExceed"] = (files) => {
upload.value!.clearFiles();
const file = files[0] as UploadRawFile;
file.uid = genFileId();
upload.value!.handleStart(file);
};
// 文件类型声明 --- 根据自己的excel字段来修改
interface tableConfigType {
knowledge: {
text: string;
type: string;
};
content: {
text: string;
type: string;
};
score: {
text: string;
type: string;
};
sort: {
text: string;
type: number;
};
}
// 定义返回数据
const tableConfig = {
knowledge: {
text: "知识点",
type: "string",
},
content: {
text: "评分内容",
type: "string",
},
score: {
text: "评分子项分值",
type: "string",
},
sort: {
text: "排序",
type: "number",
},
}
// 以二进制读取文件
const readFile = (file: any) => {
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = (e: any) => {
resolve(e.target.result);
};
});
};
const handleChange: UploadProps["onChange"] = async (uploadFile) => {
//上传的文件
let file = uploadFile.raw;
if (!file) return;
//读取上传的excel中的数据
let data: any = await readFile(file);
let workbook = XLSX.read(data, { type: "binary" });
//这里拿的是excel中第一个sheet表的数据
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
// 把数据转化为json格式
data = XLSX.utils.sheet_to_json(worksheet);
const arr: any[] = [];
data.forEach((item: any) => {
let obj: any = {};
for (let key in tableConfig) {
// 此处keyof是为了解决直接使用key索引会报错问题
let v = tableConfig[key as keyof tableConfigType];
v = item[v.text] || "";
obj[key] = v;
}
arr.push(obj);
});
// arr就是excel转化为json的数据
console.log(arr, "表格数据");
};
导入的数据格式,在tableConfigType按照自己要导入的excel中的格式进行配置。
注:genfileid()
是一个用来生成文件唯一标识符的函数。在handleExceed方法中,使用了从elementplus中引入的方法genfileid()。用来保障上传的每个文件都有唯一的标识。
这是elementplus源码中
genfileid()
方法的实现
。
const genfileid = (file) => {
return file.uid || Date.now();
};