Vue中实现Excel导入与导出功能(核心代码)[通俗易懂]

Vue中实现Excel导入与导出功能(核心代码)[通俗易懂]前言 当你在工作中遇到需要实现Excel的导入与导出完成批量添加信息时,那么就请你仔细看看这篇文章,在实际工作中,这个功能前后端是都可以实现的,如果你们公司的后端小哥哥处理好了,那么恭喜你,这篇文章你

前言

当你在工作中遇到需要实现Excel的导入与导出完成批量添加信息时,那么就请你仔细看看这篇文章,在实际工作中,这个功能前后端是都可以实现的,如果你们公司的后端小哥哥处理好了,那么恭喜你,这篇文章你就不需要看了

1.Excel导入

操作步骤

  1. 后端提供一个excel模板文件
  2. 用户填写这个excel模板文件
  3. 上传这个文件,实现批量导入功能

思路

前端主导(工作大量在前端)

上传excel文件,把excel文件的内容读出来,还原成最基本的行列结构,按后端的接口要求回传过去。

1.在 vue-admin-element中有导入方案

  • 定义组件: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.安装必要的插件

  • npm install xlsx -S

3.引入UploadExcel组件

<template>
  // 3.使用组件
  <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
</template>

<script> // 1引入组件 import UploadExcel from '@/UploadExcel/index.vue' export default { name: 'Import', components: { // 2.注册组件 UploadExcel }, 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({ header, results }) { console.log(header, results) this.tableData = results this.tableHeader = header } } } </script>

上述的两个方法是vue-admin-element提供的核心代码,直接复制过去就行

  • beforeUpload:上传之前的函数
  • onSuccess: 成功调用之后的函数

4.按接口要求,处理excel导入的数据

(1).你导入的格式是这样的

image.png (1).后台需要数据是这样的

image.png 那么你需要做的是 在onSuccess: 成功调用之后的函数的内部完成数据格式转换:将excel解析好的数据经过处理后,转成可以传给接口调用的数据

// excel文件中的日期格式的内容转回成标准时间
import { formatExcelDate } from '@/utils/index.js'

 // 成功执行的函数
    async handleSuccess({ results, header }) {
      console.log('数据是', results, header)
      this.tableData = results
      this.tableHeader = header
      // 1. 转换格式
      // const 后端要的格式 = this.format(results, header)
      const data = this.format(results)
     
      console.log('后端要的格式', data)
      // 2. 发ajax
      try {
        const res = await importEmployee(data)
        console.log('上传的结果是', res)
        this.$router.go(-1)
      } catch (err) {
        this.$message.error(err.message)
      }

      //2. 发ajax(后端要的格式)
    },

    // 起点: results: [{'姓名':'小张','工号':'9002'},{'姓名':'小王','工号':'9001'}]
    //
    //
    // 结束: [{'name':'小张','workNumber':'9002'},{'name':'小王','workNumber':'9001'}]

    // 封装后端要的格式函数
    format(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      console.log(results)
      // return []
      const res = results.map(obj => {
        // obj属性名是中文
        // 1. 取出所有的属性名 ---> 数组
        // 2 循环这个数组
        // 向newObj中补充键值对
        // 键:从中文->英文
        // 值: obj中的值
        const newObj = {}
        // 存储对象每个键为一个数组
        const zhKeys = Object.keys(obj)
        console.log(zhKeys, 'zhKeys')
        zhKeys.forEach(zhkey => {
          const enKey = mapInfo[zhkey]

          console.log(enKey)
          console.log(mapInfo[zhkey])

          console.log(obj[zhkey], 'obj') // 打印出每个对象的值

          // if(当前的key是日期相关的,要额外处理)
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            // excel中的日期格式和编程语言中的格式不一致,要转换
            // 44892 -------> 2022-11-11
            newObj[enKey] = new Date(formatExcelDate(obj[zhkey]))
          } else {
            newObj[enKey] = obj[zhkey]
          }
        })

        return newObj
      })

      return res
    }

5. excel中的日期格式和编程语言中的格式不一致

image.png 把Excel文件批量导入,Excel内部会把日期变成一个特殊的编码,这是Excel内部进行的特殊处理,那么我们需要自己封装一个函数来进行还原,还原的函数见上一篇博客,地址:juejin.cn/post/702216…

2.Excel导出

思路

  1. 将vue-element-admin中的src/vendor/export2Excel复制到本项目中,直接使用
  2. 在项目中安装依赖
  • export2Excel源码
/* eslint-disable */
import { saveAs } from 'file-saver'
import XLSX from 'xlsx'

function generateArray(table) {
  var out = [];
  var rows = table.querySelectorAll('tr');
  var ranges = [];
  for (var R = 0; R < rows.length; ++R) {
    var outRow = [];
    var row = rows[R];
    var columns = row.querySelectorAll('td');
    for (var C = 0; C < columns.length; ++C) {
      var cell = columns[C];
      var colspan = cell.getAttribute('colspan');
      var rowspan = cell.getAttribute('rowspan');
      var cellValue = cell.innerText;
      if (cellValue !== "" && cellValue == +cellValue) cellValue = +cellValue;

      //Skip ranges
      ranges.forEach(function (range) {
        if (R >= range.s.r && R <= range.e.r && outRow.length >= range.s.c && outRow.length <= range.e.c) {
          for (var i = 0; i <= range.e.c - range.s.c; ++i) outRow.push(null);
        }
      });

      //Handle Row Span
      if (rowspan || colspan) {
        rowspan = rowspan || 1;
        colspan = colspan || 1;
        ranges.push({
          s: {
            r: R,
            c: outRow.length
          },
          e: {
            r: R + rowspan - 1,
            c: outRow.length + colspan - 1
          }
        });
      };

      //Handle Value
      outRow.push(cellValue !== "" ? cellValue : null);

      //Handle Colspan
      if (colspan)
        for (var k = 0; k < colspan - 1; ++k) outRow.push(null);
    }
    out.push(outRow);
  }
  return [out, ranges];
};

function datenum(v, date1904) {
  if (date1904) v += 1462;
  var epoch = Date.parse(v);
  return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
}

function sheet_from_array_of_arrays(data, opts) {
  var ws = {};
  var range = {
    s: {
      c: 10000000,
      r: 10000000
    },
    e: {
      c: 0,
      r: 0
    }
  };
  for (var R = 0; R != data.length; ++R) {
    for (var C = 0; C != data[R].length; ++C) {
      if (range.s.r > R) range.s.r = R;
      if (range.s.c > C) range.s.c = C;
      if (range.e.r < R) range.e.r = R;
      if (range.e.c < C) range.e.c = C;
      var cell = {
        v: data[R][C]
      };
      if (cell.v == null) continue;
      var cell_ref = XLSX.utils.encode_cell({
        c: C,
        r: R
      });

      if (typeof cell.v === 'number') cell.t = 'n';
      else if (typeof cell.v === 'boolean') cell.t = 'b';
      else if (cell.v instanceof Date) {
        cell.t = 'n';
        cell.z = XLSX.SSF._table[14];
        cell.v = datenum(cell.v);
      } else cell.t = 's';

      ws[cell_ref] = cell;
    }
  }
  if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range);
  return ws;
}

function Workbook() {
  if (!(this instanceof Workbook)) return new Workbook();
  this.SheetNames = [];
  this.Sheets = {};
}

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

export function export_table_to_excel(id) {
  var theTable = document.getElementById(id);
  var oo = generateArray(theTable);
  var ranges = oo[1];

  /* original data */
  var data = oo[0];
  var ws_name = "SheetJS";

  var wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);

  /* add ranges to worksheet */
  // ws['!cols'] = ['apple', 'banan'];
  ws['!merges'] = ranges;

  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;

  var wbout = XLSX.write(wb, {
    bookType: 'xlsx',
    bookSST: false,
    type: 'binary'
  });

  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), "test.xlsx")
}

export function export_json_to_excel({ multiHeader = [], header, data, filename, merges = [], autoWidth = true, bookType = 'xlsx' } = {}) {
  /* original data */
  filename = filename || 'excel-list'
  data = [...data]
  data.unshift(header);

  for (let i = multiHeader.length - 1; i > -1; i--) {
    data.unshift(multiHeader[i])
  }

  var ws_name = "SheetJS";
  var wb = new Workbook(),
    ws = sheet_from_array_of_arrays(data);

  if (merges.length > 0) {
    if (!ws['!merges']) ws['!merges'] = [];
    merges.forEach(item => {
      ws['!merges'].push(XLSX.utils.decode_range(item))
    })
  }

  if (autoWidth) {
    /*设置worksheet每列的最大宽度*/
    const colWidth = data.map(row => row.map(val => {
      /*先判断是否为null/undefined*/
      if (val == null) {
        return {
          'wch': 10
        };
      }
      /*再判断是否为中文*/
      else if (val.toString().charCodeAt(0) > 255) {
        return {
          'wch': val.toString().length * 2
        };
      } else {
        return {
          'wch': val.toString().length
        };
      }
    }))
    /*以第一行为初始值*/
    let result = colWidth[0];
    for (let i = 1; i < colWidth.length; i++) {
      for (let j = 0; j < colWidth[i].length; j++) {
        if (result[j]['wch'] < colWidth[i][j]['wch']) {
          result[j]['wch'] = colWidth[i][j]['wch'];
        }
      }
    }
    ws['!cols'] = result;
  }

  /* add worksheet to workbook */
  wb.SheetNames.push(ws_name);
  wb.Sheets[ws_name] = ws;

  var wbout = XLSX.write(wb, {
    bookType: bookType,
    bookSST: false,
    type: 'binary'
  });
  saveAs(new Blob([s2ab(wbout)], {
    type: "application/octet-stream"
  }), `${filename}.${bookType}`);
}

2.下载export2Excel的项目依赖包

npm install file-saver script-loader xlsx --save

3.导出的数据格式转换

// 封装导出到Excel需要的格式
formatDate(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log('做格式转换', rows)
      /** * * rows: * [ * {mobile:'13612345678', username:'管理员'.....} * {mobile:'13612545678', username:'小王'.....} * ] * * * * header: [手机, 用户名] * data: [ ['13612345678', '管理员'], ['13612545678', '小王'] ] */
      // 把英文的key转成中文的表头
      const enKeys = Object.keys(rows[0])

      const header = enKeys.map(enKey => map[enKey])

      const data = rows.map(obj => {
        return Object.values(obj)
      })
      console.log(enKeys, header, data)

      return {
        header,
        data // [ ['13612345678', '管理员'], [] ]
      }
    },
    // 导出
    async hExportExcel() {
      // 1. 求数据
      const res = await getEmployeeList(this.pageParams)
      console.log('员工信息是', res.data.rows)
      // 2. 做格式转换
      const { header, data } = this.formatDate(res.data.rows)
      console.log('结果', header, data)
      // 3. 调用Export2Excel保存数据到excel

      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    }

以上是把整体的使用步骤整理了一边,你们可以自己去GitHub上面下载vue-element-admin使用,我是把核心代码都放到这个文章里,也可以直接使用

PS:里面个人觉得比较难的就是格式转换了

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/12927.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注