1、安装依赖
npm install file-saver xlsx
2、读取excel
<template>
<div>
<el-upload
style="margin-top: 20px"
class="upload-demo"
:action="'/'"
:on-progress="startUpload"
multiple
:limit="3"
:on-exceed="handleExceed"
:before-upload="handleBeforeUpload"
:show-file-list="false"
accept=".xlsx, .xls"
>
<el-button size="small" type="primary">点击上传</el-button>
</div>
</template>
import * as XLSX from "xlsx/xlsx.mjs";
import { saveAs } from "file-saver";
export default {
methods: {
handleExceed(files, fileList) {
this.$message.warning(
`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${
files.length + fileList.length
} 个文件`
);
},
async handleBeforeUpload(file) {
// 校验文件类型
const fileType = file.name.slice(file.name.lastIndexOf("."));
if (fileType !== ".xlsx" && fileType !== ".xls") {
this.$message.error("仅支持上传Excel文件");
return;
}
},
startUpload(res, file) {
const name = file.name.split(".")[1];
if (name != "xls" && name != "xlsx") {
this.$message.error("只能上传后缀为xls或xlsx的文件");
return;
}
this.handleUpload(file);
},
// 二维数组-读取excel文件第一个页签
handleUpload(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
const data = new Uint8Array(event.target.result);
const workbook = XLSX.read(data, { type: "array" });
console.log(workbook.SheetNames); //获取页签名称
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
// 检查是否存在合并单元格
if (worksheet["!merges"]) {
// 拆分单元格情况-获取合并单元格信息
const merges = worksheet["!merges"];
// 将合并单元格拆分为普通单元格
merges.forEach((merge) => {
const startRow = merge.s.r;
const endRow = merge.e.r;
const startCol = merge.s.c;
const endCol = merge.e.c;
for (let row = startRow; row <= endRow; row++) {
for (let col = startCol; col <= endCol; col++) {
if (row !== startRow || col !== startCol) {
// 复制首个单元格的值到其他拆分的单元格中
const firstCellRef = XLSX.utils.encode_cell({
r: startRow,
c: startCol,
});
const currentCellRef = XLSX.utils.encode_cell({
r: row,
c: col,
});
worksheet[currentCellRef] = { ...worksheet[firstCellRef] };
}
}
}
});
}
// 将拆分后的数据转换为JSON对象
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
resolve(jsonData);
console.log(jsonData);
};
reader.onerror = (error) => reject(error);
reader.readAsArrayBuffer(file.raw);
});
},
}
}
3、数据