如何将el-table的数据导出?

最近公司要求实现将表格内容导出,特地将方法分享出来供大家学习。

设计图:

首先需要安装两个相关依赖:

npm install --save xlsx file-saver

其次在该页面引入依赖

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

接下来前端代码,我们设置两个参数,一个name代表导出exel表的名称,一个是el-table的id,这样极大的提高了方法的复用率。

            <div class="title1-right">
              单位排名
              <el-button type="primary" size="mini" class="button" @click="exportExcel('单位排名','unit')"><i class="iconfont icon-daochuyubaodan " style="margin:10px 10px 0 0" />导出</el-button>
            </div>
          </div>
          <el-table
            id="unit"
            v-loading="loading"
            :data="tableData"
            tooltip-effect="dark"
            height="470"
            style="width: 96%;margin: 20px auto "
            :header-cell-style="{background:'#f5f7fa',color:'#909399'}"
          >
            <el-table-column
              label="排名"
              width="80"
              align="center"
              :resizable="false"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
               
                <span v-if="scope.row.ranking!=='01'&&scope.row.ranking!=='02'&&scope.row.ranking!=='03'">{
   
   { scope.row.ranking }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="单位"
              width="120"
              align="center"
              :resizable="false"
              show-overflow-tooltip
            >
              <template slot-scope="scope">{
   
   { scope.row.unit }}</template>
            </el-table-column>
            <el-table-column
              :resizable="false"
              show-overflow-tooltip
              label="优秀率"
              align="center"
            >
              <template slot-scope="scope">
                <el-progress :percentage="scope.row.percentage" />
              </template>
            </el-table-column>
          </el-table>

导出方法:

     exportExcel(name, id) {
      var wb = XLSX.utils.table_to_book(document.querySelector('#' + id))
      var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), name + '.xlsx')
      } catch (e) { if (typeof console !== 'undefined') console.log(e, wbout) }
      return wbout
    }

最终效果:

 

扫描二维码关注公众号,回复: 15947982 查看本文章

猜你喜欢

转载自blog.csdn.net/yinzisang/article/details/123796647