第一步:npm insyall xlsx
<template>
<div class="upload-content">
<a-upload
accept=".xls,.xlsx"
:showUploadList="false"
action=""
name="file"
@change="exportData"
>
<a-button type="primary"> <a-icon type="upload" /> 点击上传 </a-button>
</a-upload>
<div class="list-box" v-if="valueList.length > 0">
<span class="step-title">搜索字段:</span>
<span v-for="(i, index) in valueList" :key="index">{{ i }},</span>
</div>
<ul class="step">
<li class="step-title">操作步骤</li>
<li>
1.点击<a href="/batchTemplate.xlsx" download="搜索通用模板.xls">
下载模板 </a
>,下载导入表格模板
</li>
<li>2.请严格参照模板填充数据,否则可能无法导入数据</li>
<li>3.导入数据,每次最多导入1000条数据</li>
</ul>
<div class="modal-footer">
<a-button @click="handleModal">
取 消
</a-button>
<a-button
class="margin-left-15"
type="primary"
@click="handleModal('ok')"
>
确 认
</a-button>
</div>
</div>
</template>
<script>
import XLSX from "xlsx"
export default {
data() {
return {
valueList: []
}
},
methods: {
// 确认/关闭导入弹窗
handleModal(type) {
this.$emit("handleModal", type, this.valueList)
},
// 获取导入参数
exportData(e) {
let that = this
let length = e.fileList.length > 0 ? e.fileList.length - 1 : 0
// 拿取文件对象,注:不同框架获取到的对象可能不同,传统upload拿到的对象应该是e.target.file
var f = e.fileList[length].originFileObj
var binary = ""
var wb
var outdata
var reader = new FileReader()
reader.onload = function() {
// 读取成Uint8Array,再转换为Unicode编码(Unicode占两个字节)
var bytes = new Uint8Array(reader.result)
var length = bytes.byteLength
for (var i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i])
}
wb = XLSX.read(binary, {
type: "binary"
})
outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
that.valueList = []
outdata.forEach(item => {
let data = Object.values(item)
that.valueList = [...that.valueList, ...data]
})
}
reader.readAsArrayBuffer(f)
}
}
}
</script>
<style lang="less" scoped>
.upload-content {
width: 100%;
height: 100%;
padding: 30px;
overflow: auto;
}
.step {
width: 100%;
height: 120px;
margin-top: 20px;
li {
line-height: 30px;
}
}
.step-title {
font-weight: bold;
margin-top: 20px;
display: block;
}
.modal-footer {
display: flex;
justify-content: flex-end;
}
.list-box {
width: 100%;
max-height: 200px;
overflow: auto;
}
</style>