js上传excel文件
使用TypeScript编写,页面用到element组件库
1.页面
<el-upload
class="upload-demo"
style="float: right"
action
accept=".xlsx, .xls"
:auto-upload="false"
:show-file-list="false"
:on-change="handle"
>
<el-button size="small" type="primary">上传</el-button>
</el-upload>
2.js
// 点击上传excel文件
// element组件库 upload 里 on-change=“handle”
private handle(ev: any) {
// 拿到文件
const file = ev.raw
// 判断是否有文件信息
if (!file) return
// 通过FormData构造函数创建一个空对象
const formData = new FormData()
// 可以通过append()方法来追加数据
formData.append('file', file)
// 拿到文件信息,传给接口uploadExcle
// 异步执行接口返回的内容判断格式,回显到页面
uploadExcle(formData).then((res: any) => {
// 判断请求是否成功
if (res.data.code === 0) {
// 拿到接口返回内容
const { data } = res.data
// 判断提交格式
// 使用倒叙的方法遍历数组中的数据(因为使用splice删除时,正序删除后下标会变化)
for (let i = data.length - 1; i >= 0; i--) {
const passportNumber = data[i].passport
if (passportNumber === null) {
data.splice(i, 1)
} else if (passportNumber.length > 9) {
data.splice(i, 1)
} else if (passportNumber.length === 0) {
data.splice(i, 1)
}
}
// 判断data赋值时是否有数据
if (data.length !== 0) {
this.tableData = data
} else {
return this.$message.warning('请上传正确的文件')
}
} else {
return this.$message.warning('请上传正确的文件')
}
})
}