美文网首页
VUE----导出数据到excel

VUE----导出数据到excel

作者: JuMinggniMuJ | 来源:发表于2020-11-09 14:15 被阅读0次

我使用的是vue-cli2

1.下载包依赖:
npm install  file-saver xlsx --save
npm install  script-loader   --save
2.下载js文件到公共js文件夹:
百度网盘地址:
    链接:https://pan.baidu.com/s/1s3b8XnVxU_tscN1xidVoAg 
    提取码:hbfd 
3.说明:

我在组件中引入上面下载下来的js文件时,使用了alias相对路径,如自己使用调整相应文件路径即可:

alias:{
 'common': resolve('src/common'),
}
4.组件示例代码:
<template>
    <div>
        <el-button type="primary" @click="outexcel()">导出</el-button>
    </div>
</template>

<script>
    import {export_json_to_excel } from 'common/js/Export2Excel.js'
    export default {
        name:'MyExcel',
        props:{
            outdata:{
                type:Array,
                default:[]
            },
            titlearr:{
                type:Array,
                default:[]
            },
            fieldarr:{
                type:Array,
                default:[]
            },
            filename:{
                type:String,
                default:'excel数据导出表'
            }
        },
        methods:{
          outexcel(){
            require.ensure([], () => {
            //设置标题..
                const tHeader = this.titlearr;
            //设置数组关联字段..
                const filterVal = this.fieldarr;
            //数据集..
                const list = this.outdata;  
                const data = this.formatJson(filterVal, list);
            // excel名称可自定义
            const excelName = this.filename;
            export_json_to_excel(tHeader, data, excelName);
          });     
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      }
        }
    }
</script> 
<style scoped></style>
5.组件引用代码:
<template>
  <div>
    <my-excel :outdata="datalist" :titlearr="title" :fieldarr="field" :filename="filename"></my-excel>
  </div>
</template>
    
<script>
  import MyExcel from 'components/excel/MyExcel'
    export default {
    name:'Index',
    data() {
      return {
        datalist:[
          {date:'2020',field1:'aaaaaa',field2:'qqqq'},
          {date:'2021',field1:'bbbbbb',field2:'wwww'},
          {date:'2022',field1:'cccccc',field2:'eeee'},
          {date:'2023',field1:'dddddd',field2:'rrrr'},
          {date:'2024',field1:'eeeeee',field2:'tttt'},
          {date:'2025',field1:'ffffff',field2:'yyyy'}
        ],
        title:['张三','李四','王五'],
        field:['date','field1','field2'],
        filename:'这是excel标题啊'
      }
    },
    components:{
      MyExcel
    }
  }
</script>
6.导出数据截图:
导出数据截图
7.至此一个简单的vue导出数据就完成了

相关文章

网友评论

      本文标题:VUE----导出数据到excel

      本文链接:https://www.haomeiwen.com/subject/tymlbktx.html