<el-upload
class="upload-demo"
:action="''"
:show-file-list="false"
:auto-upload="false"
:before-upload="beforeUpload"
:on-success="handleSuccess"
:on-change="handleFileChange"
:accept="acceptString"
name="file"
>
<el-button class="opt-row-btn" slot="trigger">上传表格</el-button>
</el-upload>
async handleFileChange(file) {
console.log(file);
const dataBinary = await new Promise((resolve) => {
// Web API构造函数FileReader,可实例化对象,去调用其身上方法,去读取解析文件信息
const reader = new FileReader();
reader.readAsBinaryString(file.raw); // 读取raw的File文件
reader.onload = (ev) => {
// console.log("文件解析流程进度事件", ev);
resolve(ev.target.result); // 将解析好的结果扔出去,以供使用
};
});
const workBook = read(dataBinary, {type: 'binary', cellDates: true});
const firstWorkSheet = workBook.Sheets[workBook.SheetNames[0]];
// 分为第一行的数据,和第一行下方的数据
const header = this.getHeaderRow(firstWorkSheet);
console.log('读取的excel表头数据(第一行)', header);
const data = utils.sheet_to_json(firstWorkSheet);
console.log('读取所有excel数据', data);
this.exportVisible = false;
},
getHeaderRow(sheet) {
const headers = []; // 定义数组,用于存放解析好的数据
const range = utils.decode_range(sheet['!ref']); // 读取sheet的单元格数据
let C;
const R = range.s.r;
/* start in the first row */
for (C = range.s.c; C <= range.e.c; ++C) {
/* walk every column in the range */
const cell = sheet[utils.encode_cell({c: C, r: R})];
/* find the cell in the first row */
let hdr = 'UNKNOWN ' + C; // <-- replace with your desired default
if (cell && cell.t) hdr = utils.format_cell(cell);
headers.push(hdr);
}
return headers; // 经过上方一波操作遍历,得到最终的第一行头数据
},