欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

vue-element-admin项目导入和导出的实现

程序员文章站 2022-07-04 12:56:37
vue-element-admin导入组件封装模板和样式首先封装一个类似的组件,首先需要注意的是,类似功能,vue-element-admin已经提供了,我们只需要改造即可excel导入功能需要使用n...

vue-element-admin导入组件封装

模板和样式

vue-element-admin项目导入和导出的实现

首先封装一个类似的组件,首先需要注意的是,类似功能,vue-element-admin已经提供了,我们只需要改造即可
excel导入功能需要使用npm包xlsx,所以需要安装xlsx插件

npm i xlsx

将vue-element-admin提供的导入功能新建一个组件,位置: src/components/uploadexcel

import commontools from './commontools'
import uploadexcel from './uploadexcel'
export default {
  install(vue) {
    vue.component('commontools', commontools) // 注册工具栏组件
    vue.component('uploadexcel', uploadexcel) // 注册导入excel组件
  }
}

修改样式和布局

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

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 lang="scss">
.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

    path: '/import',
    component: layout,
    hidden: true, // 隐藏在左侧菜单中
    children: [{
      path: '', // 二级路由path什么都不写 表示二级默认路由
      component: () => import('@/views/import')
    }]
  },

创建import路由组件 src/views/import/index.vue

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

实现导入

封装导入用户的api接口

export function importuser(data) {
  return request({
    url: 'user/batch',
    method: 'post',
    data
  })
}

获取导入的excel数据, 导入excel接口

 async  success({ header, results }) {
      // 如果是导入用户
        const userrelations = {
          '入职日期': 'create_time',
          '手机号': 'mobile',
          '用户名': 'username',
          '密码': 'password',
          '邮箱': 'email',
          '部门':'部门'
        }
        const arr = []
       results.foreach(item => {
          const userinfo = {}
          object.keys(item).foreach(key => {
            userinfo[userrelations[key]] = item[key]
          })
         arr.push(userinfo) 
        })
        await importuser(arr) // 调用导入接口
        this.$router.back()
    }

为了让这个页面可以服务更多的导入功能,我们可以在页面中用参数来判断,是否是导入用户

 data() {
    return {
      type: this.$route.query.type
    }
  },

当excel中有日期格式的时候,实际转化的值为一个数字,我们需要一个方法进行转化

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 + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }

导入的手机号不能和之前的存在的手机号重复

逻辑判断

 async  success({ header, results }) {
      if (this.type === 'user') {
        const userrelations = {
          '入职日期': 'create_time',
          '手机号': 'mobile',
          '用户名': 'username',
          '密码': 'password',
          '邮箱': 'email',
          '部门':'部门'
        }
        const arr = []
        // 遍历所有的数组
        results.foreach(item => {
        // 需要将每一个条数据里面的中文都换成英文
          const userinfo = {}
          object.keys(item).foreach(key => {
          // key是当前的中文名 找到对应的英文名
            if (userrelations[key] === 'timeofentry' || userrelations[key] === 'correctiontime') {
              userinfo[userrelations[key]] = new date(this.formatdate(item[key], '/')) // 只有这样, 才能入库
              return
            }
            userinfo[userrelations[key]] = item[key]
          })
          // 最终userinfo变成了全是英文
          arr.push(userinfo)
        })
        await importuser(arr)
        this.$message.success('导入成功')
      }
      this.$router.back() // 回到上一页
    },
    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 + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }

用户页面跳转

<el-button type="warning" size="small" @click="$router.push('/import?type=user')">导入</el-button>

用户导出**

日常业务中,我们经常遇到excel导出功能, 怎么使用呢
excel 的导入导出都是依赖于js-xlsx来实现的。
在 js-xlsx的基础上又封装了export2excel.js来方便导出数据。

安装所需依赖

npm install xlsx file-saver -s
npm install script-loader -s -d

由于js-xlsx体积还是很大的,导出功能也不是一个非常常用的功能,所以使用的时候建议使用懒加载。使用方法如下:

import('@/vendor/export2excel').then(excel => {
  excel.export_json_to_excel({
    header: theader, //表头 必填
    data, //具体数据 必填
    filename: 'excel-list', //非必填
    autowidth: true, //非必填
    booktype: 'xlsx' //非必填
  })
})

excel导出参数的介绍

vue-element-admin提供了导出的功能模块,在课程资源/excel导出目录下,放置到src目录下

vue-element-admin项目导入和导出的实现

excel导出基本的结构

下面代码会用到 export2excel.js 模块,所以首先在 src 目录下新建 vendor 目录,其中新建 export2excel.js ,输入如下代码

/* 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}`);
}

因为数据中的key是英文,想要导出的表头是中文的话,需要将中文和英文做对应

 const headers = {
        '入职日期': 'create_time',
        '手机号': 'mobile',
        '用户名': 'username',
        '角色': 'role_name',
        '邮箱': 'email',
        '部门': 'department_name'
      }

完成导出代码

import { formatdate } from '@/filters'
// 导出数据
    exportdata() {
      const headers = {
        '入职日期': 'create_time',
        '手机号': 'mobile',
        '用户名': 'username',
        '角色': 'role_name',
        '邮箱': 'email',
        '部门': 'department_name'
      }
      import('@/vendor/export2excel').then(async excel => {
        const res = await getuserlist({ query: '', pagenum: 1, pagesize: this.page.total })
        // console.log(res)
        const data = this.formatjson(headers, res.users)
        console.log(data)
        excel.export_json_to_excel({
          header: object.keys(headers),
          data,
          filename: '用户信息表',
          autowidth: true,
          booktype: 'xlsx'

        })
      })
    }    
    }

导出时间格式的处理

   // 该方法负责将数组转化成二维数组
    formatjson(headers, rows) {
      return rows.map(item => {
        return object.keys(headers).map(key => {
          if (headers[key] === 'create_time') {
            return formatdate(item[headers[key]]) // formatdate 函数是定义好的一个过滤器
          }
          return item[headers[key]]
        })
      })

过滤器 formatdate

import moment from 'moment'
export function formattime(value) {
  return moment(value * 1000).format('yyyy-mm-dd hh:mm:ss')
}
export function formatdate(value) {
  return moment(value * 1000).format('yyyy-mm-dd')
}

到此这篇关于vue-element-admin项目导入和导出的实现的文章就介绍到这了,更多相关vue-element-admin项目导入导出内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!