1.npm 安装xlsx
npm i xlsx
2.创建一个ts文件 并加上以下代码
import XLSX from 'xlsx'
function xlsxTool(file: any) {
return new Promise((fn: (r: object) => void, error: () => void) => {
var reader = new FileReader();
reader.onload = function (e: any) {
try {
var data = e.target.result;
var workbook = XLSX.read(data, { type: 'binary' });
//console.log(workbook);
var datas = workbook.Sheets[workbook.SheetNames[0]];
//console.log(datas);
var allColumn = [];
for (var i = 0; i < 26; i++) {
allColumn.push(String.fromCharCode((65 + i)));
}
var hread: any = [];
var column: any = [];
allColumn.forEach(d => {
if (datas[`${d}1`] != null) {
hread.push(datas[`${d}1`].v);
column.push(d);
}
})
var objs = [];
for (var i = 2; i <= 100; i++) {
if (datas[`A${i}`] == null) {
break;
}
var obj = {};
column.forEach((d: any, ii: number) => {
(obj as any)[`${hread[ii]}`] = datas[`${d}${i}`] == null ? "" : datas[`${d}${i}`].v;
})
objs.push(obj);
}
//console.log(objs);
fn(objs);
}
catch (errorMsg) {
error();
}
};
reader.readAsBinaryString(file);
})
}
export default xlsxTool
3.在要使用的页面导入上面的ts文件
import xlsx from "../../api/exam/xlsx";
4.定义file隐藏域
<input type="file" hidden id="qb_file" @change="table.fileChange" />
5.点击按钮时触发file点击事件
//打开文件选择
openFile: () => {
let qb_file: any | null = document.getElementById("qb_file");
qb_file.value = null; //清空上次选择的文件
qb_file.click();
},
6.file发生更改时触发的事件
//当文件改变时
fileChange: () => {
let qb_file: any | null = document.getElementById("qb_file");
const fileName = qb_file.value;
if (fileName != undefined && fileName != null && fileName != "") {
const fileExtension = fileName.substring(
fileName.lastIndexOf(".") + 1
);
if (fileExtension == "xlsx") {
console.log(qb_file.files[0]);
xlsx(qb_file.files[0]).then((r: any) => {
var questions: any = []; //临时存放questions对象的集合
r.forEach((item: any) => {
questions.push({
//将导出的数据装入临时集合
topicDry: item.题干,
topic: item.题型,
options: item.选项.split("|,|"),
lv: item.难度,
type: item.类型,
});
});
testQuestions.questions = questions; //将临时集合的数据给真正的集合
});
} else {
//选择的不是xlsx文件
ElNotification({
title: "错误",
message: "请选择正确文件",
type: "error",
});
}
} else {
//没有选择文件
ElNotification({
title: "错误",
message: "请选择文件再操作",
type: "error",
});
}
},
结果:
![](https://i-blog.csdnimg.cn/blog_migrate/c88f272cde5384a58365744b933d5bf2.png)