«

怎么使用vue实现前端导入excel数据

时间:2024-5-24 15:38     作者:韩俊     分类: Javascript


这篇文章主要介绍“怎么使用vue实现前端导入excel数据”,在日常操作中,相信很多人在怎么使用vue实现前端导入excel数据问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”怎么使用vue实现前端导入excel数据”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

一、主界面先引入导入组件

1.这段主要是中间的那段excel-import标签的那部分代码,loadList是后边导入成功后,子组件要调用的方法,这个方法是导入成功后,刷新表格数据的

  <a-space class="crud-buttons">
                <a-button @click="handleEdit" type="primary">
                    <a-icon type="edit"></a-icon>
                    修改
                </a-button>
                <excel-import @fatherMethod="loadList"></excel-import>
                <a-button @click="exportData" type="danger" :loading="btnLoading">  <a-icon type="upload" />导出</a-button>
                <a-button type="primary" @click="grantWelfare">
                    <a-icon type="plus"></a-icon>
                    发放
                </a-button>
            </a-space>

路径根据你们的要求自行修改

import excelImport from "../../components/excel-import"

二、封装excel-import组件

1.首先是template代码(这里用的是ant vue desgin框架的组件)

<template>
    <div class="import">
        <a-button @click="exportData" type="primary"><a-icon type="import" />导入</a-button>
        <a-modal v-model="visible" title="导入数据" @ok="handleOk"  @cancel="handleCancel" width="400px">
            <a-upload-dragger :file-list="fileList" :multiple="false"
                              :before-upload="beforeUpload" :remove="removeFile">
                <p class="ant-upload-drag-icon">
                    <a-icon type="inbox"/>
                </p>
                <p class="ant-upload-hint">
                    仅允许导入xls、xlsx格式文件
                </p>
            </a-upload-dragger>
        </a-modal>
 
    </div>
</template>

2.引入接口

import WelfareApi from '@/api/master/welfare'

3.js代码methods

exportData(){
                this.visible=true
            },
          async handleOk(){
                if (this.data.length === 0) {
                    this.$message.error("请选择要上传的文件")
                } else {
                    const data=await WelfareApi.importExcelData(this.data)
                    this.$message.success(data.message)
                    this.visible=false;
                    this.fileList=[]
                    this.$emit('fatherMethod');
                }
            },
            handleCancel(){
            this.fileList=[]
            this.visible=false
            },
            // 文件上传前的钩子
            beforeUpload(file) {
                const isXslx =
                    file.type ===
                    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || file.type === "application/vnd.ms-excel";
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isXslx) {
                    this.$message.error("附件格式错误,请删除后重新上传!");
                }
                if (isXslx) {
                    if (this.fileList.length == 0) {
                        this.fileList = [...this.fileList, file]
                        this.importfxx(this.fileList);
                    } else {
                        this.$message.error("仅能选择一个文件进行上传!")
                    }
                }
                if (!isLt2M) {
                    this.$message.error("上传文件大小不能超过 2MB!");
                }
                return false
            },
            removeFile(file) {
                const index = this.fileList.indexOf(file);
                const newFileList = this.fileList.slice();
                newFileList.splice(index, 1);
                this.fileList = newFileList;
            },
            importfxx(obj) {
                let _this = this;
                let inputDOM = this.$refs.inputer;
                // 通过DOM取文件数据
 
                this.file = event.currentTarget.files[0];
 
                let rABS = false; //是否将文件读取为二进制字符串
                let f = this.file;
 
                let reader = new FileReader();
                FileReader.prototype.readAsBinaryString = function (f) {
                    let binary = "";
                    let rABS = false; //是否将文件读取为二进制字符串
                    let pt = this;
                    let wb; //读取完成的数据
                    let outdata;
                    let reader = new FileReader();
                    reader.onload = function (e) {
                        let bytes = new Uint8Array(reader.result);
                        let length = bytes.byteLength;
                        for (let i = 0; i < length; i++) {
                            binary += String.fromCharCode(bytes[i]);
                        }
                        //此处引入,用于解析excel
                        let XLSX = require("xlsx");
                        if (rABS) {
                            wb = XLSX.read(btoa(fixdata(binary)), {
                                //手动转化
                                type: "base64"
                            });
                        } else {
                            wb = XLSX.read(binary, {
                                type: "binary"
                            })
                        }
                        outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
                        //outdata就是读取的数据(不包含标题行即表头,表头会作为对象的下标)
                        //此处可对数据进行处理
                        let arr = [];
                        outdata.map(v => {
                            let obj = {}
                            obj.id = v['序号']
                            obj.dpStage = v['DP班号']
                            obj.traineeName = v['学员姓名']
                            obj.name = v['收货人姓名']
                            obj.mobile = v['收货人电话']
                            obj.province = v['省']
                            obj.city = v['市']
                            obj.district = v['区']
                            obj.detailAddr = v['详细地址']
                            obj.expressName = v['快递名称']
                            obj.expressNumber = v['快递编号']
                            obj.expressTime = v['发货时间']
                            obj.statusName = v['状态']
                            arr.push(obj)
                        });
                        _this.data=arr;
                        _this.dalen=arr.length;
                        return arr;
                    };
                    reader.readAsArrayBuffer(f);
                };
                if (rABS) {
                    reader.readAsArrayBuffer(f);
                } else {
                    reader.readAsBinaryString(f);
                }
            }

这里有几点注意的地方

在对outdata处理的时候,例如obj.id=v['序号']

这里的id就是传给后端的对象集合中对象的属性名,后端也要用对应的model接收

这里的序号就是excel表格的表头列名,一定要文字对应,不然会导入失败

三.附加提示(后端也要写的小伙伴可以参考下边建议哈)

我们传给后端的数据,应该是一个集合形式,在后端一般需要对数据进行处理,因为我们要把数据insert到我们的数据库中去,当然可能会有重复的数据(比如说导入的是用户信息,数据库里存在这个人的,你要导入的excel也存在)如果要求是修改的话,这时候就要根据的唯一标识(id,或者是电话、身份证号等等)来分情况做处理到底是新增还是修改。最后我还建议可以设置两个变量,一个来记录成功导入数据库的记录数量,一个记录覆盖(修改)记录的数量,然后返回给前端。

标签: javascript vue

热门推荐