Use vue to realize front-end import of excel data

Article directory


foreword

Following the previous vue export function, I searched for some articles on vue importing excel on the Internet, and realized the function of vue importing excel by organizing and adjusting the code.


1. The main interface first introduces the import component

1. This section is mainly the part of the code of the excel-import tag in the middle. loadList is the method to be called by the subcomponent after the import is successful. This method is to refresh the table data after the import is successful.

  <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>

  The path can be modified according to your requirements

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

2. Encapsulate the excel-import component

1. The first is the template code (the components of the ant vue desgin framework are used here)

<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 interface

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

3. js code 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);
                }
            }

Here are a few things to keep in mind

When processing outdata, for example obj.id=v['serial number']

The id here is the attribute name of the object in the object collection passed to the backend, and the backend should also receive it with the corresponding model

The serial number here is the header column name of the excel table, which must correspond to the text, otherwise the import will fail

3. Additional hints (friends who also need to write in the back end can refer to the suggestions below)

The data we pass to the backend should be in the form of a collection. Generally, the data needs to be processed at the backend, because we need to insert the data into our database. Of course, there may be duplicate data (for example, the imported user Information, the person exists in the database, and the excel you want to import also exists) If the request is to modify, then it must be processed according to the unique identifier (id, or phone number, ID number, etc.) Whether to add or modify. Finally, I also suggest that two variables can be set, one to record the number of records successfully imported into the database, and one to record the number of overwritten (modified) records, and then return to the front end.


Four. Summary

The above is what I want to talk about today. This article introduces the use of vue to import excel, mainly to process the excel to be imported at the front end, and finally transfer the sorted data to the back end and add it to the database. Thank you guys for watching!

Guess you like

Origin blog.csdn.net/m0_61101835/article/details/128147486
Recommended