所需包
bash
"xlsx": "^0.18.5"
页面导入包
bash
import * as XLSX from 'xlsx';
import {genFileId, UploadProps, UploadRawFile,ElTable } from 'element-plus';
页面
bash
<el-upload accept=".xlsx" :on-change="changeExcel" :on-exceed="handleExceed" :limit="1" :auto-upload="false" :show-file-list="false" ref="upload">
<el-button type="primary" size="default">导入Excel</el-button>
</el-upload>
//js
let tableData=ref([])
const upload = ref<InstanceType<typeof ElTable>>();
const handleExceed: UploadProps['onExceed'] = (files) => {
upload.value!.clearFiles();
const file = files[0] as UploadRawFile;
file.uid = genFileId();
upload.value!.handleStart(file);
};
function changeExcel(e, fileList) {
console.log('changeExcelProject---------->');
if (fileList.length > 1) {
fileList.splice(0, 1);
}
const files = e.raw;
console.log('files------>', files);
// 读取表格
const fileReader = new FileReader();
fileReader.onload = (ev) => {
const workbook = XLSX.read(ev.target.result, {
type: 'binary',
});
const wsname = workbook.SheetNames[0];
const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname], {
defval: '',
});
console.log('ws=', ws); // 转换成json的数据
//可以选择构建列
let columnsproject = [];
if (ws && ws.length > 0) {
const obj = ws[0] as Object;
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
columnsproject.push({
label: key,
prop: key,
});
}
}
}
tableDataproject.value = [...ws];
fieldMap.set('姓名', 'name');
fieldMap.set('年龄', 'age');
fieldMap.set('性别', 'sex');
let tableDataArr = [...ws];
let dataNew: any[] = [];
for (let i = 0; i < tableDataArr.length; i++) {
const item = tableDataArr[i];
const obj: any = buildingObj(item);
dataNew.push(obj);
}
tableData.value=dataNew
console.error("tableData",tableData)
};
fileReader.readAsBinaryString(files);
}
function buildingObj(item: object) {
const obj = {};
for (const [key, value] of fieldMap) {
obj[value] = item[key];
}
return obj;
}