废话不说,直接上代码
首先前端是一个上传文件的组件,第一步加载文件,第二部导入,在导入的时候就会触发方法对Excel进行解析,转化为json数据!
<p-fileUpload name="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" chooseLabel="批量申请" uploadLabel="批量导入" cancelLabel="取消导入" customUpload="true" (uploadHandler)='uploadHandler($event)'> </p-fileUpload>
下面是实现的前端效果:
下面是实现转换的主要js:
/** * 将解析的json数据分装到一个临时数组 * @param event */ uploadHandler(event) { this.parseXlsxToJson(event.files[0]).subscribe(resp => { this.up = resp; this.up.forEach(element => { // delete element['xuhao']; element['字段1'] = element['字段1'].trim(); // element['字段2'] = element['字段2'].trim(); // }); console.log("打印up") console.log(this.up) if (this.up.length != 0) { this.msgs = [{ severity: 'success', summary: '', detail: '模板导入成功!' }]; } else { this.msgs = [{ severity: 'error', summary: '', detail: '模板数据为空,请核对!' }]; } }); } /** * 将excel数据解析成Json格式数据 * 将json数据对象的属性名称转换成字段名称 * @param fileData */ parseXlsxToJson(fileData: Blob): Observable<any> { return this.parseXlsx(fileData, (ws) => { // 将json数据对象的属性名称转换成字段名称 this.fileSource.next(XLSX.utils.sheet_to_json(ws, { raw: false, range: 1, header: ['字段1', '字段2'] })); }); } /** *解析excel内容 */ private parseXlsx(fileData: Blob, callBack: Function): Observable<any> { this.reader.onload = function (e) { const data = new Uint8Array(e.target['result']); const workbook = XLSX.read(data, { type: 'array' }); const wsname: string = workbook.SheetNames[0]; const ws = workbook.Sheets[wsname]; callBack(ws); }; this.reader.readAsArrayBuffer(fileData); if (this.fileSource) { this.fileSource = new Subject(); } return this.fileSource.asObservable(); }
最终解析的数据: