1. 程式人生 > 實用技巧 >Vue+element 實現表格匯出xlsx格式

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>

如圖: