廢話不說,直接上代碼
首先前端是一個上傳文件的組件,第一步加載文件,第二部導入,在導入的時候就會觸發方法對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();
}
最終解析的數據:

