1.安装xlsx
npm install xlsx
2.组件封装
通过input标签是先上传并读取文件内容
<template>
<label class="custom-file-upload">
<i class="el-icon-folder-add" />
<div>
{{ name }}
</div>
<input
id="fileInput"
type="file"
:value="files"
accept=".xlsx"
@change="handleFileUpload"
>
</label>
</template>
<script>
import * as XLSX from 'xlsx'
export default {
props: {
name: {
type: String,
default: '导入'
}
},
data() {
return {
files: '',
data: []
}
},
methods: {
handleFileUpload(event) {
const file = event.target.files[0]
const formData = new FormData()
formData.append('file', file)
const reader = new FileReader()
reader.onload = (e) => {
const binaryString = e.target.result
const workbook = XLSX.read(binaryString, { type: 'binary' })
const worksheet = workbook.Sheets[workbook.SheetNames[0]]
const jsonData = XLSX.utils.sheet_to_json(worksheet)
this.$emit('upload', jsonData)
}
reader.readAsBinaryString(file)
}
}
}
</script>
<style lang="scss" scoped>
/* 自定义file类型的input */
#fileInput {
display: none;
}
.custom-file-upload {
height: 29px;
background-color: #ffffff;
border: 1px solid #dcdcdc;
border-radius: 3px;
cursor: pointer;
color: #606266;
font-size: 12px;
padding: 0 14px;
font-weight: 400;
display: flex;
align-items: center;
justify-content: center;
margin: 0 10px 0 0;
div{
margin-left: 5px;
}
}
.custom-file-upload:hover {
background-color: #f5f5f5;
}
</style>