<!-- 封装的模板下载和导入按钮和功能组件-->
<template> <span style="margin-left: 10px"> <el-button size="mini" class="el-icon-download" @click="downFiles"> 下载模板</el-button> <el-upload action="" style="width: 115px;display: inline-block;margin-left: 10px" :http-request="uploadSectionFile" :on-success="handleAvatarSuccess" :before-upload="beforeUpload" :show-file-list="false" :accept="accept" > <el-button class="el-icon-upload" size="mini">批量导入</el-button> </el-upload> </span> </template> <script> import XLSX from 'xlsx'
import Blob from './Excel/Blob'
import Export2Excel from './Excel/Export2Excel.js'
export default { name: 'importTemplate', data() { return { accept: '.xlsx', fileTemp: {}, // 导入的文件流 tableData: [] } }, methods: { downFiles() { // <a href="./static/培训实施参加人员统计模板.xlsx"><i className="el-icon-download"/>下载模板</a> window.open('/static/培训实施参加人员统计模板.xlsx') }, uploadSectionFile(uploader) { this.fileTemp = uploader.file if (this.fileTemp) { if ((this.fileTemp.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (this.fileTemp.type === 'application/vnd.ms-excel')) {
this.importfEx(this.fileTemp) } else { this.$message({ type: 'warning', message: '附件格式错误,请删除后重新上传!' }) } } else { this.$message({ type: 'warning', message: '请上传附件!' }) } }, importfEx(event) { // FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容 const fileReader = new FileReader() const file = event // 回调函数 fileReader.onload = ev => { try { const data = ev.target.result const workbook = XLSX.read(data, { type: 'binary' }) // excel读取出的数据 const excelData = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]) // 将上面数据转换成 table需要的数据---将获取到的数据$emit抛出数据 this.$emit('changeImportData', excelData) } catch (e) { this.$message({ type: 'error', message: '文件类型不正确!' }) return false } } // 读取文件 成功后执行上面的回调函数 fileReader.readAsBinaryString(file) }, handleAvatarSuccess(res, file) { console.log(res) // this.vm.edit.data.contractProjects.push({}) }, beforeUpload(file) { if (this.accept !== '') { const index = file.name.indexOf('.') const type = file.name.substring(index + 1, file.name.length) if (this.accept.indexOf(type) === -1) { this.$message.error(`文件 ${file.name}格式不正确,请上传指定格式的文件 ${this.accept}`) return false } } } } } </script> <style scoped> </style>
<!-- 2. 父组件调用封装的组件-->
<template>
<!-- //导入excel 下载模板组件-->
<import-template @changeImportData="changeImportDataFun" />
</template>
methods: {
changeImportDataFun(dataArr) {
// 返回的数组数据
},
}
标签:vue,const,name,excel,获取数据,fileTemp,file,message,type From: https://www.cnblogs.com/Z-HarOld/p/17318507.html