npm 下载 xlsx
package.json
"xlsx": "^0.18.5"
utils/readFile.js
export const readFile = (file) => {
return new Promise(resolve => {
const reader = new FileReader();
reader.onload = (ev:any) => {
resolve(ev.target.result);
};
reader.readAsBinaryString(file);
});
};
.vue 文件
<template>
<el-upload
class="inline m_r_12"
action=""
:show-file-list="false"
accept=".xls,.xlsx"
:on-change="uploadChange"
>
<el-button>上传</el-button>
</el-upload>
</template>
<script lang="ts" setup>
import { readFile } from "@/utils/readFile.js";
import * as XLSX from "xlsx";
//文件解析解析excel
const uploadChange: UploadProps["onSuccess"] = async (response, uploadFile) => {
let data;
//读取文件 file,并在读取完后将值赋值给
data = await readFile(uploadFile[(uploadFile as any).length - 1].raw);
//利用XLSX的方法,将数据转换成可读数据
let workbook = XLSX.read(data, { type: "binary" });
//获取excel表格第一个Sheet页签的数据
let worksheet = workbook.Sheets[workbook.SheetNames[0]];
//将数据转换成接送对象
data = XLSX.utils.sheet_to_json(worksheet);
let arr = [];
data.forEach((item) => {
let obj = {
subject_name: item["题目"],
answer: item["答案"],
};
arr.push(obj as never);
});
//批量新增
batchAddApi({
question_bank_id: route.query.id,
data: JSON.stringify(arr),
}).then((res) => {
console.log("res", res);
getList();
});
};
<scirpt>