excel导入功能实现

建立公共导入的页面路由

excel导入功能需要使用npm包xlsx,所以需要安装xlsx插件

$ npm i xlsx

** 创建公共组件UploadExcel并全局注册**
这里其中里面的功能我们了解即刻,别人(vue-element-admin)已经帮我们写好,

<template>
  <div class="upload-excel">
    <div class="btn-upload">
      <el-button :loading="loading" size="mini" type="primary" @click="handleUpload">
        点击上传
      </el-button>
    </div>

    <input
      ref="excel-upload-input"
      class="excel-upload-input"
      type="file"
      accept=".xlsx, .xls"
      @change="handleClick"
    />
    <div class="drop" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
      <i class="el-icon-upload" />
      <span>将文件拖到此处</span>
    </div>
  </div>
</template>

<script>
// import XLSX from 'xlsx'
import * as XLSX from 'xlsx/xlsx.mjs'
export default {
  name: 'uploadExcel',
  props: {
    beforeUpload: Function, // eslint-disable-line
    onSuccess: Function // eslint-disable-line
  },
  data() {
    return {
      loading: false,
      excelData: {
        header: null,
        results: null
      }
    }
  },
  methods: {
    generateData({ header, results }) {
      this.excelData.header = header
      this.excelData.results = results
      this.onSuccess && this.onSuccess(this.excelData)
    },
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      if (this.loading) return
      const files = e.dataTransfer.files
      if (files.length !== 1) {
        this.$message.error('Only support uploading one file!')
        return
      }
      const rawFile = files[0] // only use files[0]
      if (!this.isExcel(rawFile)) {
        this.$message.error('Only supports upload .xlsx, .xls, .csv suffix files')
        return false
      }
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      if (!rawFile) return
      this.upload(rawFile)
    },
    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel
      if (!this.beforeUpload) {
        this.readerData(rawFile)
        return
      }
      const before = this.beforeUpload(rawFile)
      if (before) {
        this.readerData(rawFile)
      }
    },
    readerData(rawFile) {
      this.loading = true
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet)
          this.generateData({ header, results })
          this.loading = false
          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name)
    }
  }
}
</script>

<style lang="less" scoped>
.upload-excel {
  display: flex;
  justify-content: center;
  margin-top: 100px;
  .excel-upload-input {
    display: none;
    z-index: -9999;
  }
  .btn-upload,
  .drop {
    border: 1px dashed #bbb;
    width: 350px;
    height: 160px;
    text-align: center;
    line-height: 160px;
  }
  .drop {
    line-height: 80px;
    color: #bbb;
    i {
      font-size: 60px;
      display: block;
    }
  }
}
</style>

新建一个公共的导入页面,挂载路由 src/router/index.js
创建import路由组件 src/views/import/index.vue
:on-success="success"就是我们自己要写的功能

<template>
  <!-- 公共导入组件 --> 
  <upload-excel :on-success="success" />
</template>

分析excel导入代码,封装接口

/** *
 *
 * 用户导入
 * **/
export function excelUsers(data) {
  return request({
    method: 'post',
    url: '/user/excelUsers',
    data
  })
}

为了让这个页面可以服务更多的导入功能,我们可以在页面中用参数来判断,是否是导入用户(‘/import?type=user’),用this.$route.query.type来接收

import { excelUsers } from '@/api/user'
export default {
  name: 'importPage',
  data() {
    return {
      type: this.$route.query.type
    }
  },
  methods: {
    async success({ header, results }) {
      // header表头 result数据
      // 判断是否为导入用户
      if (this.type === 'user') {
        const userRelations = {
          '用户名': 'username',
          '密码': 'password',
          '手机号': 'mobile',
          '单元': 'unit',
          '门牌号': 'rootNumber',
          '籍贯': 'native',
          '类型': 'type'
        }
        const newArr = []
        // 处理数据成数组对象类型传给后端
        results.forEach((item) => {
          const userInfo = {}
          Object.keys(item).forEach((key) => {
            userInfo[userRelations[key]] = item[key]
          })
          newArr.push(userInfo)
        })
        
        await excelUsers(newArr) // 后端接口
        this.$message.success('导入成功')
        this.$router.back()
      }
    }
  }
}

node部分代码

const db = require('../../db/index')

module.exports = (req, res) => {
  const data = req.body
  const newArr = []
  // 数据处理成 [['张三','1380000001','123456'],['李四','1380000001','123456']]格式
  data.forEach((item) => {
    const arr = []
    for (var key in item) {
      // console.log(item[key])
      arr.push(item[key])
    }
    newArr.push(arr)
  })
  const sqlStr =
    'insert into t_users (username,mobile,password,unit,rootNumber,native,type) values ?'
  db.query(sqlStr, [newArr], (err, result, fields) => {
    if (err) {
      console.log(err)
      return res.status(400).send({
        message:
          err.code === 'ER_DUP_ENTRY' && err.errno === 1062
            ? 'excel文件中手机号或门牌号重复或已被占用,请检查完毕在重新提交'
            : '发生未知错误'
      })
    }
    if (result.affectedRows > 0) {
      return res.send({
        success: true,
        message: '导入成功',
        data: result
      })
    } else {
      return res.status(500).send({
        success: false,
        message: '导入失败'
      })
    }
  })
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值