1.安装依赖

npm install file-saver --save

npm install xlsx --save

npm install script-loader --save-dev

2.下载需要的js文件Blob.js和 Export2Excel.js

下载链接:https://download.csdn.net/download/liuxiaoxiaosmile/10345153

3.在项目src目录下新建vendor文件夹,将Blob.js和 Export2Excel.js放进去

4.更改webpack.base.conf.js配置,加入

'vendor': path.resolve(__dirname, '../src/vendor')

效果如下:

resolve: {
  extensions: ['.js', '.vue', '.json'],
  alias: {
    'vue$': 'vue/dist/vue.esm.js',
    '@': resolve('src'),
    'vendor': path.resolve(__dirname, '../src/vendor')
  }
}
 

5.在.vue文件中使用

data() {
      return {
        itemList: [
      {
          name:'红木',
          type:'P000001',
          price:'¥88888'
      },
      {
          name:'水杉',
          type:'P000002',
          price:'¥2000'
      }
    ]
      }
    }

在method里面增加两个方法:

formatJson(filterField, jsonData) {
        return jsonData.map(function(dataObj){
            return filterField.map(function(field){
                let fieldObj = dataObj[field];
                if(utils.isEmpty(fieldObj)){
                  fieldObj = "--";
                }
              return fieldObj;
            });
        });

      },
 export2Excel() {
	  require.ensure([], () => {
            let { export_json_to_excel } = require('@/vendor/Export2Excel');
            let tHeader = ['名称','类型','价格'];
            let filterField = ['title', 'type','price'];
            let list = this.itemList;
            let data = self.formatJson(filterField, list);
            let timeFormat = moment().format("YYYYMMDDHHmmss");
            let title      = "产品列表" + timeFormat;
            export_json_to_excel(tHeader, data, title);
          })
 }

6.在template里面添加button

<el-button @click="export2Excel"  style="position:absolute;right:16px;">导出</el-button>
7.界面上点击button按钮即可在浏览器中导出文件
Logo

前往低代码交流专区

更多推荐