vue-element-表格 Excel 【导入】功能 (2023元旦快乐~~~)

news2024/9/23 1:48:50

一、页面表格导入功能

我们借鉴vue-element-admin文件来学习表格导入功能,如果你有vue-element-admin的完整文件,可以去这里找

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-E8ETjTCk-1672500415985)(C:\Users\28132\AppData\Roaming\Typora\typora-user-images\1672474245053.png)]
or 用我这里的代码

1. 整体复制到你要用到的页面

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

export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(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
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
    }
  }
}
</script>

然后 ----注意导入文件!

  • 将vue-element-admin中的src/components/UploadExcel 文件拖入到自己项目中,存放在相同位置,如果修改位置记得在导入的地方修改路径
    在这里插入图片描述

  • or 复制这里的文件到src/components/UploadExcel/index.vue

<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>
import XLSX from 'xlsx'

export default {
  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 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>

2. 下载xlsx文件

由于admin中的xlsx版本不一样,我们需要下载它的版本,在package.json可以看到版本

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-sAUEnsEl-1672500415987)(C:\Users\28132\AppData\Roaming\Typora\typora-user-images\1672474513815.png)]

我们直接复制到自己项目中的package.json相同位置

 "xlsx": "0.14.1"

然后在控制台下载依赖

npm  i

3. 重启服务器,测试是否能上传Excel,正确效果如下

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CAoQH2Q8-1672500415988)(C:\Users\28132\AppData\Roaming\Typora\typora-user-images\1672474640736.png)]

二、表格导入格式转换

原本格式:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LD1BssCW-1672500415988)(C:\Users\28132\AppData\Roaming\Typora\typora-user-images\1672478594240.png)]

转化后格式:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ih1KJpjO-1672500415990)(C:\Users\28132\AppData\Roaming\Typora\typora-user-images\1672478624741.png)]

转换函数:

// 表格数据转换函数
export function transformData(result) {
  const mapInfo = {
    '入职日期': 'timeOfEntry',
    '手机号': 'mobile',
    '姓名': 'username',
    '转正日期': 'correctionTime',
    '工号': 'workNumber',
    '部门': 'departmentName',
    '聘用形式': 'formOfEmployment'
  }
  return result.map(item => {
    const zhKeys = Object.keys(item)
    const obj = {}
    zhKeys.forEach(zhKey => {
      const enKey = mapInfo[zhKey]
      if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
        obj[enKey] = formatExcelDate(item[zhKey])
      } else {
        obj[enKey] = item[zhKey]
      }
    })
    return obj
  })
}
// 转换表格时间为2021/1/2格式
export function formatExcelDate(numb, format = '/') {
  const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
  time.setYear(time.getFullYear())
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() + ''
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}

使用函数转换:

 handleSuccess({ results, header }) {
      console.log(results, header)//表格的初始数据
      this.tableData = results
      this.tableHeader = header
      const data = transformData(results)//调用函数转换格式
      console.log(data)//最终得到图2效果---因为后台需要这样的数据
    }

如果需要转换为标准格式可以用new Date():(18行)

// 表格数据转换函数
export function transformData(result) {
  const mapInfo = {
    '入职日期': 'timeOfEntry',
    '手机号': 'mobile',
    '姓名': 'username',
    '转正日期': 'correctionTime',
    '工号': 'workNumber',
    '部门': 'departmentName',
    '聘用形式': 'formOfEmployment'
  }
  return result.map(item => {
    const zhKeys = Object.keys(item)
    const obj = {}
    zhKeys.forEach(zhKey => {
      const enKey = mapInfo[zhKey]
      if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
        obj[enKey] = new Date(formatExcelDate(item[zhKey]))
      } else {
        obj[enKey] = item[zhKey]
      }
    })
    return obj
  })
}
// 转换表格时间为2021/1/2格式
// 把excel文件中的日期格式的内容转回成标准时间
export function formatExcelDate(numb, format = '/') {
  const time = new Date((numb - 25567) * 24 * 3600000 - 5 * 60 * 1000 - 43 * 1000 - 24 * 3600000 - 8 * 3600000)
  time.setYear(time.getFullYear())
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() + ''
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
}


现在是2022年12.31号晚上23:37分,马上又是充满希望的一年~
加油加油! O(∩_∩)O

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/132438.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

unreal engine 纹理动态运动的实现

先用ps涉及一张图,发光的地方为白色 下图实际上边缘是相连的白色 split_line.jpgue新建材质 基础色vector3 随便选择一个偏灰的颜色 自发光 TextureCoordirate ->Panner->图片rgb->*发光常量 * 20自发光 预览效果 通过修改纹理协调器的V垂直平铺控制条纹数量 image.pn…

mybatis插件

Configuration组成 Mapper映射器 3个部分组成&#xff1a; MappedStatement 保存一个节点(select | insert | update | delete) &#xff0c;包括我们配置的sql&#xff0c;&#xff0c;sql的id&#xff0c;&#xff0c;缓存信息&#xff0c;&#xff0c;resultMap,parameterT…

Redis高并发锁(三)分布式锁

在很多情况下&#xff0c;你的数据库不支持事务&#xff0c;分布式部署也使得你无法去使用JVM锁&#xff0c;那么这种时候&#xff0c;你可以考虑用分布式锁 文章目录分布式锁1. 实现方式2. 特征3. 操作4. 代码改造5. 测试优化1. 递归改成循环2. 防止死锁3. 防误删4. LUA脚本 保…

Arduino code for RS-365PW 16120

Pictures These pictures are from Baidu Search. Picture 1: Installment Picture 2: Appearance Picture 3: Encoder of Motor Picture 4: Pins location and number Physical Specification Brand: Mabuchi Motor (万宝至电机)Type: RS-365PW 16120 Body length&#xff1…

学生抢课接口(高并发入门)

目录 使用Mysql 常规测试 张三测试 流程总结 redis优化 修改代码 测试 使用分布式锁 总结 使用Mysql 常规测试 原始代码: Override Transactional public ResponseResult selectCourse(SelectParmas selectParmas) {if (Objects.isNull(selectParmas)){return new …

【python游戏】新的一年快来变身兔兔战士打败獾守护兔兔吧~

前言 大家早好、午好、晚好吖 ❤ ~ 一只快乐兔&#xff0c; 来到快乐山&#xff0c;喝了快乐泉&#xff0c; 又到快乐殿&#xff0c;吃了快乐莲&#xff0c;遇到快乐仙&#xff0c; 听了快乐言&#xff1a;快乐很简单&#xff0c;快乐在身边&#xff0c;快乐无极限&#xff…

C++中STL的vector扩容机制

目录前言发生扩容扩容机制size()和capacity()reserve()和resize()前言 前阵子面试的时候&#xff0c;被问到往vector中插入一个数据可能会发生什么&#xff1f; 我答:可能会扩容; 为啥vector支持变长&#xff1f; 我答:它实在堆上动态申请内存&#xff0c;因此有自己的一套扩容…

Redis集群系列十 —— 集群伸缩之收缩

集群收缩原理 集群收缩就是让其中一些节点安全下线。 所谓的安全下线指的是让一个节点下线之前&#xff0c;把其负责的所有 slots 迁移到别的节点上&#xff0c;否则该节点下线后其负责的 slots 就没法继续提供服务了。 收缩流程如下&#xff1a; 需求 前面扩容完成后&…

字符串大小写转化,有序数组二分查找个人心得等若干内容

tips 1. 在电脑里面&#xff0c;任何一切字符&#xff0c;当一看到的时候&#xff0c;脑子里面就要把它转化成ACSII值。如while(0)&#xff0c;可以实现死循环。 2. 统计整形数组的长度不能用strlen()&#xff0c;别一天到晚用到底&#xff0c;strlen统计的是字符数组的长度 …

在wsl下开发T113的主线linux(1)-准备wsl开发环境

首先在win10或win11下安装wsl&#xff0c;选择wsl1或者wsl2都可以&#xff0c;wsl2的性能更高一些&#xff0c;wsl1的跨系统文件操作速度更快一些&#xff0c;我这里因为有一些工程在win文件系统下&#xff0c;所以选择了wsl1&#xff0c;发行版使用最新的Ubuntu 22.04.01 LTS。…

MySQL隐式转换

隐式转换概念 When an operator is used with operands of different types, type conversion occurs to make the operands compatible. Some conversions occur implicitly. 当运算符与不同类型的操作数一起使用时&#xff0c;将进行类型转换以使操作数兼容。某些转换是隐式发…

2022年年终总结---新方向,新期待

2022年行将结束&#xff0c;回首年初立下的flag&#xff1a; (1)完成OpenCoord版本升级&#xff0c;增加ITRF框架及历元转换、EGM2008查询功能&#xff1b; (2)完成多波束开源项目的数据读取和显示操作。 任务(1)已经完成了&#xff0c;任务&#xff08;2&#xff09;没有完成。…

力扣(LeetCode)2351. 第一个出现两次的字母(C++)

哈希集合 开哈希集合&#xff0c;遍历字符串&#xff0c;未出现的字母加入哈希集合&#xff0c;如果字母出现过&#xff0c;返回这个字母即可。 class Solution { public:char repeatedCharacter(string s) {unordered_set<char> S;for(auto &c:s)if(!S.count(c)) …

第二证券|72家公司接待机构过千,迈瑞医疗热度“断层领先”

2022年最终一个交易日&#xff0c;沪指以红盘收官&#xff0c;但年内A股商场震荡起伏&#xff0c;三大指数均收跌&#xff0c;其间&#xff0c;沪指全年下跌15%&#xff0c;创业板指跌近三成。 调研活动是出资者挖掘上市公司信息的重要来源&#xff0c;是洞悉商场主力资金意向的…

记录NCNN Yolov5部署华为鸿蒙系统踩过的坑

目录 踩坑一&#xff1a;Android Studio连接鸿蒙系统踩过的坑 踩坑二&#xff1a;配置Android studio环境 踩坑三&#xff1a;打开文件夹的位置 踩坑四&#xff1a;No toolchains found in the NDK toolchains folder for ABI with prefix: arm-linux-androideabi 总结 踩…

使用 Bitnami Helm 安装 Kafka

服务器端 K3S 上部署 Kafka Server Kafka 安装 &#x1f4da;️ Quote: charts/bitnami/kafka at master bitnami/charts (github.com) 输入如下命令添加 Helm 仓库&#xff1a; > helm repo add tkemarket https://market-tke.tencentcloudcr.com/chartrepo/opensource-…

LinuxShell注意事项

Linux 介绍 内存 虚拟内存 = 物理内存 + 交换空间 交换空间 = 交换空间 当用户访问某一个程序内存时,需要访问物理内存,而不是交换内存,如果物理内存没有,而交换内存有,则会将交换内存中的程序 加载进物理内存供用户使用,同样,当一个程序长期未访问,内核会将物理内…

【Mongoose笔记】Websocket 服务器

【Mongoose笔记】Websocket 服务器 简介 Mongoose 笔记系列用于记录学习 Mongoose 的一些内容。 Mongoose 是一个 C/C 的网络库。它为 TCP、UDP、HTTP、WebSocket、MQTT 实现了事件驱动的、非阻塞的 API。 项目地址&#xff1a; https://github.com/cesanta/mongoose学习 …

Chromium Embedded Framework(CEF)源码编译基于windows

1.打开维基百科CEF主页: Chromium Embedded Framework - Wikipedia 2.找到CEF仓库地址:chromiumembedded / cef — Bitbucket 打开CEF源码仓库: 点击 Wiki,然后在 Getting Started节,点击cef-project 向下拉浏览滚动条,可看到Setup章节

第三十二讲:神州交换机和路由器上分别实现QoS

QoS&#xff08;Quality of Service&#xff0c;服务品质保证&#xff09;是指一个网络能够利用各种各样的技术向选定的网络通信提供更好的服务的能力。QoS是服务品质保证&#xff0c;提供稳定、可预测的数据传送服务&#xff0c;来满足使用程序的要求&#xff0c;QoS不能产生新…