Vue+element 实现表格导出xlsx格式

Vue+element 实现表格导出xlsx格式

1、安装

npm install file-saver xlsx --save
cnpm install file-saver xlsx --save //淘宝镜像

2、新建一个文件夹daochubiaoge放daochubiaoge.js

import FileSaver from 'file-saver'
import XLSX from 'xlsx'

export  function fileXlsx(biaogeName,id) {
    let time = new Date()
    let year = time.getFullYear()
    let month = time.getMonth() + 1
    let day = time.getDate()
    let name = biaogeName + year + '' + month + '' + day
    // console.log(name)
    /* generate workbook object from table */
    //  #table要导出的是哪一个表格
    var wb = XLSX.utils.table_to_book(document.querySelector(id))
    /* get binary string as output */
    var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array',
    })
    try {
        //  name+'.xlsx'表示导出的excel表格名字
        FileSaver.saveAs(
            new Blob([wbout], { type: 'application/octet-stream' }),
            name + '.xlsx'
        )
    } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
    }
    return wbout
}

3、在需要的vue文件中引用

 <template>
    <div>
        <el-table :data="tableData" style="width: 100%" id="table">
        <el-table-column prop="date"  label="日期" width="180"> </el-table-column>
        <el-table-column prop="name" label="姓名" width="180"></el-table-column>
        <el-table-column prop="address" label="地址"></el-table-column>
      </el-table>
      <el-button @click="exportExcel">导出</el-button>
    </div>
 </template>
 
 <script>
  import * as FileSaver from '@/daochubiaoge/daochubiaoge'
   export default {
       data() {
         return {
           tableData: [{
             date: '2016-05-02',
             name: '王小虎',
             address: '上海市普陀区金沙江路 1518 弄'
           }, {
             date: '2016-05-04',
             name: '王小虎',
             address: '上海市普陀区金沙江路 1517 弄'
           }, {
             date: '2016-05-01',
             name: '王小虎',
             address: '上海市普陀区金沙江路 1519 弄'
           }, {
             date: '2016-05-03',
             name: '王小虎',
             address: '上海市普陀区金沙江路 1516 弄'
           }]
         }
       },
         methods: {
           exportExcel () {
             FileSaver.fileXlsx('表格1-','#table')
           }
         }
 }
</script>

如图:

 

 

 

 

posted @ 2020-12-26 14:50  童话里都是骗人的  阅读(553)  评论(0编辑  收藏  举报