Excel Upload文件上传、UI解析

2021-03-08  本文已影响0人  前端小慵卿
image.png

input标签中type为file显示的是比较传统的file上传UI标签。

<!--html:-->
<div class="upload-file" (click)="chooseFile.click()">
     <span *ngIf="fileName">{{fileName}}</span>
     <span class="placeholder" *ngIf="fileName === null">Choose xlsx/xls file (max file size 10M)...</span>
     <i nu-icon [name]="'0325_file_selector'" class="file-icon"></i>
     <input type="file" class="file" #chooseFile (change)="getFile($event)" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
</div>
// scss:
.upload-file{
  border: 1px solid #CCCCCC;
  padding-left: 10px;
  height: 34px;
  line-height: 34px;
  position: relative;
  background: #FFFFFF;
  margin-bottom: 20px;
  &:hover {
    cursor: pointer;
  }
}
.placeholder{
  color: #999999;
}
.file-icon{
  position: absolute;
  right: 10px;
  top: 10px;
}
.file{
  position: absolute;
  width: 100%;
  top:0;
  left: 0;
  bottom: 0;
  display: none;
}
// ts:
getFile(event) {
  // 获取上传文件的name
  this.fileName = event.target.files[0].name;
  // 获取文件的type
  const fileType = this.fileName.substring(this.fileName.lastIndexOf('.') + 1).toLowerCase();
  const reader: FileReader = new FileReader();
  // size 的单位转换为M
  let size = event.target.files[0].size; // byte
  size = size / 1024; // kb
  size = size / 1024; // mb
  //解析文件
  reader.onload = (e: any) => {
     const bstr: string = e.target.result;
     const wb: XLSX.WorkBook = XLSX.read(bstr, {type: 'binary'});
     const firstSheet: string = wb.SheetNames[0];
     const ws: XLSX.WorkSheet = wb.Sheets[firstSheet];
     // 去掉字段名的空格及* 
     ws.A1.w = ws.A1.w.replace(/\s/g, '');
     ws.A1.w = ws.A1.w.replace('*', '');
     ....(省略其他标签的操作,重复代码)
     const data: FileData[] = XLSX.utils.sheet_to_json(ws);
     // data即为获取的解析的数据
  }
}

上一篇下一篇

猜你喜欢

热点阅读