1.下载xlsx类库,npm install xlsx --save
2.html,使用input标签,可以自定义样式,进行文件上传
<a href="javascript:;" class="file">
<input type="file" name="" (change)="importf($event)" accept="application/vnd.ms-excel,.xlsx,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
id="" />导入数据
</a>
3.ts,接受文件类型,进行解析
import * as XLSX from 'xlsx'; //引入核心类
inputdata: any; //定义转换后的数据
importf(evt: any) { //input的change时间
/* wire up file reader */
const target: DataTransfer = <DataTransfer>(evt.target); //接受文件
if (target.files.length !== 1) throw new Error('Cannot use multiple files');
const reader: FileReader = new FileReader(); //采用reader解析文件
let max = target.files[0].size; //取得文件带下
let that = this;//修改作用域
reader.onprogress = function (evt) //处理进度条
{
that.Percent = evt.loaded/max *100 ;
}
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];
/* save data */
this.inputdata = (XLSX.utils.sheet_to_json(ws));
console.log(this.inputdata)
this.updon(this.inputdata);
evt.target.value = "" // 清空
};
reader.readAsBinaryString(target.files[0]);
}
updon(data) {
// 实现自己的业务,调用接口
this.toolService.Import(this.checkData(data)).then(data => {
if(data.Result == 0){
this.message.success('导入成功');
}else{
this.message.error('导入失败');
}
});
}