vue + xlsx实现Excel导出

简单粗暴步骤,无需花里胡哨

  • 第一步:npm install --save xlsx@0.14.3
  • 第二步:全局封装公共方法(或者局部定义)
import XLSX from "xlsx";

let common = {
  install: function ($Vue) {
    let Vue = $Vue.prototype;
    let common = {
      // 导出excel表格
      // data:导出参数,name:表格名称,cols: 每列宽度
      exportExcel(data, name, cols = []) {
        let sheet = XLSX.utils.aoa_to_sheet(data)
        sheet['!cols'] = cols
        this.downExcel(this.sheetBlob(sheet), name)
      },
      downExcel(url, saveName) {
        if (typeof url === 'object' && url instanceof Blob) {
          url = URL.createObjectURL(url) // 创建blob地址
        }
        let aLink = document.createElement('a')
        aLink.href = url
        aLink.download = saveName || '' // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,file:///模式下不会生效
        let event
        if (window.MouseEvent) event = new MouseEvent('click')
        else {
          event = document.createEvent('MouseEvents')
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        }
        aLink.dispatchEvent(event)
      },
      // 将一个sheet转成最终的excel文件的blob对象,然后利用URL.createObjectURL下载
      sheetBlob(sheet, sheetName) {
        sheetName = sheetName || 'sheet1'
        let workbook = {
          SheetNames: [sheetName],
          Sheets: {}
        }
        workbook.Sheets[sheetName] = sheet
        // 生成excel的配置项
        let wopts = {
          bookType: 'xlsx', // 要生成的文件类型
          bookSST: false, // 是否生成Shared String Table,官方解释是,如果开启生成速度会下降,但在低版本IOS设备上有更好的兼容性
          type: 'binary'
        }
        let wbout = XLSX.write(workbook, wopts)
        let blob = new Blob([s2ab(wbout)], {
          type: 'application/octet-stream'
        })
        // 字符串转ArrayBuffer
        function s2ab(s) {
          if (typeof ArrayBuffer !== 'undefined') {
            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;
          } else {
            var buf = new Array(s.length);
            for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
            return buf;
          }
        }
        return blob
      }
    }
    // 将公共方法复制到原型上
    Vue.$common = common;
  }
}

export default common;
  • 第三步:main.js 中引入common
// 调用公共方法
import common from './views/utils/common'
Vue.use(common);
  • 第四步: 组装数据
exportExcel: function () {
  let aoa = [['姓名']]
   // 整理设备列表的数组元素
  for (let i = 0; i < this.dataList.length; i++) {
  	let a = this.dataList[i]
  	let itemDevice = [a.name]
    aoa.push(itemDevice)
   }
  // 设置列宽
  let cols = [
  	{ wch: 10 }
   ]
   this.$common.exportExcel(aoa, '表格.xlsx', cols)
},
Logo

前往低代码交流专区

更多推荐