Vue3 Avue Excel导入导出两种方法

发布时间 2023-08-24 14:55:19作者: 骄傲一点才可爱

Vue3 Avue Excel导入导出两种方法

1.根据avue官网,直接使用

官网导入导出地址

在index.html里导入包

<!-- 导入需要的包 (一定要放到index.html中的head标签里)-->
<script src="https://cdn.staticfile.org/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<script src="https://cdn.staticfile.org/xlsx/0.18.2/xlsx.full.min.js"></script>

不需要安装插件直接使用

<template>
  <div style="display:flex;">
    <el-button type="primary"
               @click="handleGet">下载模版</el-button>
    <div style="width:20px;"></div>
    <el-upload :auto-upload="false"
               :show-file-list="false"
               action="action"
               :on-change="handleChange">
      <el-button type="primary">导入 excel</el-button>
    </el-upload>
  </div>
  <br />
  <avue-crud :option="option"
             :data="list"></avue-crud>
</template>
<script>
export default {
  data () {
    return {
      list: [],
      option: {
        column: [{
          label: 'id',
          prop: 'id'
        }, {
          label: '姓名',
          prop: 'name'
        }, {
          label: '年龄',
          prop: 'sex'
        }]
      }
    }
  },
  methods: {
    handleGet () {
      window.open('/cdn/demo.xlsx')
    },
    handleChange (file, fileLis) {
      this.$Export.xlsx(file.raw)
        .then(data => {
          this.list = data.results;
        })
    }
  }
}
</script>

2.使用插件(这个插件必须导入需要的包,不然拿不到数据)

https://gitee.com/smallweigit/avue-plugin-excel/

根据上面地址里的使用步骤直接实现。

提示:必须要导入这个包 ↓


<!-- 导入需要的包 (一定要放到index.html中的head标签里)-->
<script src="https://cdn.staticfile.org/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<script src="https://cdn.staticfile.org/xlsx/0.18.2/xlsx.full.min.js"></script>
yarn 使用这个命令安装
yarn add avue-plugin-excel --save     

完整代码如下:

<template>
  <div style="display:flex;">
    <el-button type="primary"
               @click="handleGet">下载模版</el-button>
    <div style="width:20px;"></div>
    <el-upload :auto-upload="false"
               :show-file-list="false"
               action="action"
               :on-change="handleChange">
      <el-button type="primary">导入 excel</el-button>
    </el-upload>
  </div>
  <br />
  <avue-crud :option="option"
             :data="list"></avue-crud>
</template>
<script>
import $Excel from 'avue-plugin-excel';
export default {
  data() {
    return {
      list: [],
      option: {
        column: [
          {
            label: 'id',
            prop: 'id',
          },
          {
            label: '姓名',
            prop: 'name',
          },
          {
            label: '年龄',
            prop: 'sex',
          },
        ],
      },
    };
  },
  methods: {
    handleGet() {
      window.open('/cdn/demo.xlsx');
    },
    handleChange(file, fileLis) {
      $Excel.xlsx(file.raw).then(data => {
        console.log(data.results); //导出的json数组
      });
    },
  },
};
</script>