记录--Vue中如何导出excel表格

这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助

一、导出静态数据

1、安装 vue-json-excel

npm i vue-json-excel

注意,此插件对node有版本要求,安装失败检查一下报错是否由于node版本造成!

2、引入并注册组件(以全局为例)

import Vue from "vue";
import JsonExcel from "vue-json-excel"; //引入excel插件
Vue.component("downloadExcel", JsonExcel);//注册

3、使用

在template节点下使用download-excel标签即可

    <download-excel class="downloadExcel" :data="dataAttr" types="xls" :fields="fields" :name="exportName"
      :worksheet="exportSheet" :header="exportName" :footer="exportFooter" :defaultValue="exportDefaultValue">
      <el-button type="success">导出</el-button>   //可以无需button
    </download-excel>

在data节点下定义数据

dataAttr: [
        {
          id: 1,
          name: '九转大肠',
          price: 999,
          sellCount: 6,
          rating: 100
        }],
      fields: { // 数据名称及对应的值
        编号: 'id',
        名称: 'name',
        价格: 'price',
        销量: 'sellCount',
        好评率: {
          field: 'rating',
          callback: value => `${value}%` // 以对象方式可以对数据做处理
        }
      },
      exportName: '这是表格名称',
      exportSheet: '这是表格sheet的名称',
      exportHeader: '这是表格的标题',
      exportFooter: '这是表格的页脚',
      exportDefaultValue: '这是一个默认的数据'

点击导出

二、导出动态数据

如果需要在点击按钮前动态的获取数据,则需要使用fetch属性来指定一个参数。

注意,使用此参数时不能再绑定data参数

以导出一个外卖商品列表为例: 

1、为fetch属性绑定了一个回调。

    <download-excel class="downloadExcel" :fetch="getDataAttr" types="xls" :fields="fields" :name="exportName"
      :worksheet="exportSheet" :header="exportName" :footer="exportFooter" :defaultValue="exportDefaultValue">
      <el-button type="success">导出{
     
     { exportName }}</el-button>
    </download-excel>

2、在methods节点下定义方法

getDataAttr() {
      const dataAttr = []     //定义导出数据
      this.goodsList.forEach((value) => {   //进行数据处理
        let dataAttrItem = new createExcleData(value.id, value.name, value.price,  value.sellCount, value.rating) 
         //使用引入的createExcleData
        dataAttr.push(dataAttrItem) //为导出的数据数组添加数据
      })
      return dataAttr //数据整理完毕
    },

3、新建一个js文件封装一个类创建每条数据

export default class DataAttr {
  constructor(id, name, price, sellCount, rating) {
    this.id = id;
    this.name = name,
    this.price = price,
    this.sellCount = sellCount,
    this.rating = rating;
  }
}

4、在组件下引入,然后就可以使用了

import createExcleData from '@/utils/createExcleData' 

goodsList数据如下

点击导出,打开导出文件

本文转载于:

https://juejin.cn/post/7204742703506522171

如果对您有所帮助,欢迎您点个关注,我会定时更新技术文档,大家一起讨论学习,一起进步。

 

猜你喜欢

转载自blog.csdn.net/qq_40716795/article/details/130788390