html
<a (click)="import()">导入</a> <input #importExcelInput [hidden]="true" type="file" (change)="onFileChange($event)" multiple="false" />
ts
import() { let input = this.importExcelInput.nativeElement; input.value = ''; input.click(); } //导入 async onFileChange(evt: any) { this.isTableLoading = true; let self = this; return new Promise(function (resolve, reject) { /* wire up file reader */ const target: DataTransfer = <DataTransfer>evt.target; if (target.files.length !== 1) throw new Error('无法上传多个文件'); const reader: FileReader = new FileReader(); reader.readAsBinaryString(target.files[0]); let itemList: any[] = []; reader.onload = async (e: any) => { /* read workbook */ const bstr: string = e.target.result; const wb: WorkBook = read(bstr, { type: 'binary' }); /* grab first sheet */ const wsname: string = wb.SheetNames[0]; const ws: WorkSheet = wb.Sheets[wsname]; const lengthStr = ws['!ref'].split(':')[1]; const rowLength = parseInt(lengthStr.replace(/[^\d]/g, ' ')); for (let index = 2; index <= rowLength; index++) { var entity: any = {}; entity.name = ws[`A${index}`] ? ws[`A${index}`].v.toString() : null; entity.num = ws[`B${index}`] === undefined ? 0 : ws[`B${index}`].v; entity.amount = ws[`C${index}`] === undefined ? 0 : ws[`C${index}`].v; entity.taxRate = ws[`D${index}`] === undefined ? TaxRateEnum['13%'] : ws[`D${index}`].v; if (!entity.name) { self.notify.error('必填项存在为空!!!,请矫正后重试'); self.isTableLoading = false; reject(); break; } var reg = /^[0-9]*$/; var reg2 = /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/; if (!reg.test(entity.num) || !reg2.test(entity.amount) || !reg2.test(entity.taxRate)) { self.notify.error('存在数字类型数据非法!!!,请矫正后重试'); self.isTableLoading = false; reject(); break; } itemList.push(entity); resolve(itemList); } }; }).then(itemList => { // console.log(itemList); this.service .getSparePartInfoByImport(itemList) .pipe( finalize(() => { this.isTableLoading = false; }) ) .subscribe(data => { this.notify.success('导入成功'); var ls: any = []; var index = 0; if (this.dataList.length >= 1) { index = this.dataList[this.dataList.length - 1].index + 1; } data.map(i => { i.index = index; index++; }); ls.push(...this.dataList); ls.push(...data); this.dataList = ls; }); }); }
标签:index,const,target,dataList,SheetJs,导入,ls,数据 From: https://www.cnblogs.com/sugarwxx/p/17919260.html