前言

因项目有需要在前端进行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:

  1. <nz-upload [nzAction]="'#'" [nzCustomRequest]="importExcel" [nzShowUploadList]="false" (nzChange)="fileChange($event)">
  2. <button nz-button><i nz-icon nzType="upload"></i><span>导入Excel</span></button>
  3. </nz-upload>
  1. [nzCustomRequest]:覆盖文件上传的默认行为,此处只需要读取文件,不需要上传文件至服务器
  2. [nzShowUploadList]:无需显示上传文件列表
  3. (nzChange):文件上传回调

对应ts方法:

  1. import * as XLSX from 'xlsx';
  2. type AOA = any[][];
  3. fileChange({file, type}) {
  4. if (type === 'start') {
  5. // 文件改变会产生3个状态,start process end,这里只在start时进行excel解析
  6. const reader = new FileReader();
  7. reader.onload = (e: any) => {
  8. /* read workbook */
  9. const bstr: string = e.target.result;
  10. const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
  11. /* grab first sheet */
  12. const wsname: string = wb.SheetNames[0];
  13. const ws: XLSX.WorkSheet = wb.Sheets[wsname];
  14. this.data = (XLSX.utils.sheet_to_json(ws, {header: 1})) as AOA;
  15. console.log(this.data);
  16. };
  17. reader.readAsBinaryString(file.originFileObj);
  18. }
  19. }
  20. importExcel({}) {
  21. // 覆盖文件上传的默认行为,这里只需读取解析excel文件,并不需要上传文件。未返回Subscription会产生一个warning
  22. return null;
  23. }

最后会将Excel表的内容以一个二维数组的形式存储在data中

相关链接

Angular
NG-ZORRO
SheetJS