前言
因项目有需要在前端进行Excel解析,所以选择使用SheetJS来解析Excel实现相应的功能。使用到的库:Angular,NG-ZORRO,SheetJS。默认你已经创建好Angular项目,正确引入NG-ZORRO与SheetJS
包版本:Angular-10.2.0,Antd-10.2.0,xlsx-0.16.9,@types/xlsx-0.0.36
实现
html:
<nz-upload [nzAction]="'#'" [nzCustomRequest]="importExcel" [nzShowUploadList]="false" (nzChange)="fileChange($event)"><button nz-button><i nz-icon nzType="upload"></i><span>导入Excel</span></button></nz-upload>
- [nzCustomRequest]:覆盖文件上传的默认行为,此处只需要读取文件,不需要上传文件至服务器
- [nzShowUploadList]:无需显示上传文件列表
- (nzChange):文件上传回调
对应ts方法:
import * as XLSX from 'xlsx';type AOA = any[][];fileChange({file, type}) {if (type === 'start') {// 文件改变会产生3个状态,start process end,这里只在start时进行excel解析const reader = new FileReader();reader.onload = (e: any) => {/* read workbook */const bstr: string = e.target.result;const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});/* grab first sheet */const wsname: string = wb.SheetNames[0];const ws: XLSX.WorkSheet = wb.Sheets[wsname];this.data = (XLSX.utils.sheet_to_json(ws, {header: 1})) as AOA;console.log(this.data);};reader.readAsBinaryString(file.originFileObj);}}importExcel({}) {// 覆盖文件上传的默认行为,这里只需读取解析excel文件,并不需要上传文件。未返回Subscription会产生一个warningreturn null;}
最后会将Excel表的内容以一个二维数组的形式存储在data中
