1.导入弹窗
<el-dialog :title="upload.title" :visible.sync="upload.open1"
:close-on-click-modal = "false"
:show-close="false" width="400px" append-to-body>
<el-upload
accept=".xlsx, .xls"
action=""
:show-file-list="true"
:file-list="fileList"
:on-change="getFile"
:auto-upload="false" drag>
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或
<em>点击上传</em>
</div>
<div class="el-upload__tip" slot="tip">
<el-link type="info" style="font-size:12px;color: #f70000;" @click="downloadTemplate">下载模板</el-link>
</div>
<div class="el-upload__tip" style="color:red" slot="tip">提示:仅允许导入“xls”或“xlsx”格式文件!</div>
</el-upload>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="importAll">导 入</el-button>
<el-button @click="cancelUpload">取 消</el-button>
</div>
</el-dialog>
2.保证一次上传可见文件为最后一个
if (fileList.length > 0) {
this.fileList = [fileList[fileList.length - 1]] // 这一步,是 展示最后一次选择的文件
}
3.onchange方法获取上传的本地file
async getFile(item, fileList){
this.arr = [];
if (fileList.length > 0) {
this.fileList = [fileList[fileList.length - 1]] // 这一步,是 展示最后一次选择的文件
}
let file = item.raw
if (!file) return
let reader = await upload(file)
const worker = xlsx.read(reader, { type: 'binary' })
// 将返回的数据转换为json对象的数据
reader = xlsx.utils.sheet_to_json( worker.Sheets[worker.SheetNames[0]])
// 注意这里的表头一定要和excel表头一致,不然就会报错,建议粘贴复制过来
reader.map(v => {
const obj = {}
obj.name = v['工序名']
obj.standardtime = v['标准时间(秒:s)']
obj.price = v['单价(元)']
obj.note = v['备注']
this.arr.push(obj)
})
},
4.upload方法:
return new Promise(resolve=>{
let reader = new FileReader()
reader.readAsBinaryString(file);
reader.onload = ev=>{
resolve(ev.target.result)
}
})
}
5.在3中解析了上传的excel之后,得到了一个json类型的数组,这里我采用的方法就是遍历数组然后将数组中的每一个json数组单独请求一次新增数据接口,直到所有的数据添加成功则表示导入成功!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。