vue+el-upload实现上传excel

本文介绍如何在Vue项目中利用el-upload组件上传Excel文件。通过配置action、show-file-list、before-upload和http-request等属性实现上传功能。在before-upload中进行校验,若设置auto-upload为false,则需在http-request中处理请求。成功上传后,可通过on-success回调处理返回数据并展示在页面上。
摘要由CSDN通过智能技术生成

先大概了解一下这个组件的属性和方法:
在这里插入图片描述
action:看官网就知道了,指定上传的路径,但是一般vue项目里我们的请求路径不会写在这里。
show-file-list:是否显示你上传的文件,true的话它会在一个ul里显示
before-upload:顾名思义,上传之前的一些操作,我把校验写在这里了。
注意::auto-upload="false"时before-upload不生效,所以她两选择一个便好。

 beforeUpload(file) {
   
        const Xls = file.name.split('.'
以下是一个基于 VueElement UI 的导入 Excel 的示例代码: ```vue <template> <div> <el-upload class="upload-excel" :before-upload="beforeUpload" :on-success="onUploadSuccess" :on-error="onUploadError" :file-list="fileList" :accept=".xlsx,.xls" :auto-upload="false" > <el-button slot="trigger" type="primary">选择文件</el-button> <el-button slot="append" type="success" :disabled="!fileList.length" @click="uploadExcel">上传</el-button> <div slot="tip" class="el-upload__tip">只能上传 .xlsx 或 .xls 文件</div> </el-upload> </div> </template> <script> import XLSX from 'xlsx' export default { data() { return { fileList: [] } }, methods: { beforeUpload(file) { // 校验文件类型 const isXLS = file.type === 'application/vnd.ms-excel' const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' const isExcel = isXLS || isXLSX if (!isExcel) { this.$message.error('只能上传 .xlsx 或 .xls 文件') return false } // 添加到 fileList 中 this.fileList.push(file) return false // 阻止自动上传 }, onUploadSuccess(response) { // 上传成功后的处理逻辑 this.$message.success('上传成功!') }, onUploadError(error) { // 上传失败后的处理逻辑 this.$message.error('上传失败!') }, uploadExcel() { // 读取 Excel 文件内容,此处使用了 xlsx 库 const file = this.fileList[0] const reader = new FileReader() reader.onload = (e) => { const data = e.target.result const workbook = XLSX.read(data, { type: 'binary' }) const sheetName = workbook.SheetNames[0] const worksheet = workbook.Sheets[sheetName] const json = XLSX.utils.sheet_to_json(worksheet) console.log(json) // 打印 Excel 数据 } reader.readAsBinaryString(file.raw) } } } </script> ``` 解释一下: 1. 组件中包含一个 `el-upload` 组件,用于上传 Excel 文件。 2. `beforeUpload` 方法用于校验文件类型,并将文件添加到 `fileList` 中。 3. `onUploadSuccess` 和 `onUploadError` 分别是上传成功和上传失败的回调函数。 4. `uploadExcel` 方法用于读取 Excel 文件内容,使用了 `xlsx` 库将 Excel 数据转换成 JSON 数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值