vue 弹框组件封装, excel,xlsx,xls 多文件上传
在Vue中封装一个支持Excel文件上传的弹框组件,可以使用element-ui
的Upload
组件来实现文件上传功能,并使用xlsx
库来解析Excel文件。以下是一个简单的示例:
- 安装所需依赖:
npm install element-ui xlsx
- 封装组件:
<template>
<el-dialog title="导入Excel" :visible.sync="dialogVisible" @close="resetUpload">
<el-upload
ref="upload"
action="#"
:auto-upload="false"
:on-change="handleFileChange"
:before-upload="beforeUpload"
:on-exceed="handleExceed"
:limit="1"
accept=".xlsx, .xls">
<el-button slot="trigger" size="small" type="primary">选择文件</el-button>
<div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件</div>
</el-upload>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="submitUpload">确 定</el-button>
</span>
</el-dialog>
</template>
<script>
import XLSX from 'xlsx';
export default {
data() {
return {
dialogVisible: false,
file: null,
};
},
methods: {
open() {
this.dialogVisible = true;
},
handleFileChange(file, fileList) {
this.file = file.raw;
},
beforeUpload(file) {
const isExcel = /\.(xlsx|xls)$/.test(file.name);
if (!isExcel) {
this.$message.error('只能上传Excel文件!');
return false;
}
return true;
},
handleExceed(files, fileList) {
this.$message.warning(`只能上传 1 个文件,当前已选择 ${files.length + fileList.length} 个`);
},
submitUpload() {
if (this.file) {
const reader = new FileReader();
reader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const json = XLSX.utils.sheet_to_json(worksheet);
this.$emit('on-success', json);
this.resetUpload();
};
reader.readAsArrayBuffer(this.file);
}
},
resetUpload() {
this.$refs.upload.clearFiles();
this.file = null;
},
},
};
</script>
- 使用封装的组件:
<template>
<div>
<excel-uploader @on-success="handleSuccess"></excel-uploader>
</div>
</template>
<script>
import ExcelUploader from './ExcelUploader.vue';
export default {
components: {
ExcelUploader,
},
methods: {
评论已关闭