上传excel文件

该博客介绍了如何使用Vue组件实现Excel文件的上传和导入功能。通过监听文件选择和拖放事件,结合xlsx库解析Excel数据,并在上传前进行校验。同时,提供了将解析后的数据转换为接口所需的格式,以便进一步处理和导入。文章还展示了如何在后台接口中处理这些导入的数据,并在前端展示表格。
摘要由CSDN通过智能技术生成

 

<template>
  <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">
      Drop excel file here or
      <el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
        Browse
      </el-button>
    </div>
  </div>
</template>

<script>
// 核心的解析三方插件 作用就是把excel文件解析为js格式
// xlsx库经过一些更新 导入的方式发生了一些变化
// 解决: 把导入的方式换成最新的导入
import * as XLSX from 'xlsx'

export default {
  // 可以容许传入的参数
  props: {
    // 解析之前进行的回调函数 作用:对excel文件做一些校验 比如大小 格式
    beforeUpload: Function, // eslint-disable-line
    // 解析成功之后自动执行的回调函数 类型函数  作用:拿到excel解析之后的数据
    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 scoped>
.excel-upload-input{
  display: none;
  z-index: -9999;
}
.drop{
  border: 2px dashed #bbb;
  width: 600px;
  height: 160px;
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
</style>

 

/**
 * @description: 获取导出时的表头数据和表格数据
 * @param {*} { sourceData:后端返回的源数据,header:表格头中因为对应关系}
 * @return {*}
 */

// 处理函数中对key判断如果发生当前它是聘用形式 通过枚举做一下处理 返回中文

// 枚举处理函数 根据1/2返回正式或者非正式
function transEmployment(value) {
  const TYPES = {
    1: '正式',
    2: '非正式'
  }
  return TYPES[value]
}

export function getExportData(sourceData, headerRelation) {
  const data = sourceData.map(item => {
    const arr = []
    Object.values(headerRelation).forEach(key => {
      // 关键位置:把所有的value不做任何处理直接扔到了数组中 导致excel是源数据
      // 如果是当前要处理的是聘用形式 就先转化一步再添加到数组中
      if (key === 'formOfEmployment') {
        const formatValue = transEmployment(item[key])
        arr.push(formatValue)
      } else {
        arr.push(item[key])
      }
    })
    return arr
  })
  return {
    data
  }
}

/**
 * @description: 获取导入时的处理之后的接口数据
 * @param {*} results
 * @return {*}
 */
export function getImportJsData(results, headerRelation) {
  const newArr = []
  // 将所有的中文key转换成英文key 然后添加到新数组中
  results.forEach(item => {
    const map = {}
    Object.keys(item).forEach(key => {
      map[headerRelation[key]] = item[key]
    })
    newArr.push(map)
  })
  // 时间处理
  newArr.forEach(item => {
    Object.keys(item).forEach(key => {
      if (key === 'timeOfEntry') {
        item[key] = new Date(formatDate(item[key], '/'))
      }
    })
  })
  return newArr
}

export function formatDate(numb, format) {
  const time = new Date((numb - 1) * 24 * 3600000 + 1)
  time.setYear(time.getFullYear() - 70)
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() - 1 + ''
  if (format && format.length === 1) {
    return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
  }
  return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}

<template>
  <div class="app-container">
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
    <el-table
      :data="tableData"
      border
      highlight-current-row
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column
        v-for="item of tableHeader"
        :key="item"
        :prop="item"
        :label="item"
      />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { getImportJsData } from '@/utils/excel'
import { fetchImportExcel } from '@/api/employee'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data () {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    // 解析之前执行的校验函数
    // 在函数内部如果通过了校验 比如return true
    // 否则就return false 当return的值是false的时候解析逻辑执行会被停止
    beforeUpload (file) {
      // file excel文件对象
      console.log(file)
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 解析之后执行的回调成功函数
    async handleSuccess ({ results, header }) {
      // results: 对象数组 表体数据
      // header: 数组 表体数据
      console.log(results, header)
      // 把插件产出的数据转化成接口要求的格式  getImportJsData
      const headerRelation = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName'
      }
     
      const result = getImportJsData(results, headerRelation)
      console.log(result)
      await fetchImportExcel(result)
      this.$message.success('导入成功')
      // 跳回去
      this.$router.back()
      this.tableData = results
      this.tableHeader = header
    }
  }
}
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值