vue + elemen-UI实现table数据导出到Excel

  • 根据业务需求添加导出Excel功能,首先在vue下安装相关依赖
npm install --save xlsx file-saver
  • 然后在<script> </script> 块中引入相关组件
 import FileSaver from 'file-saver'
 import XLSX from 'xlsx'
  •  table列表如下,导出的Excel表头将根据table列出的属性进行匹配
       <!--导出Excel表格  tableDataExcel:保存列表数据的数组   export-table: 为el-table组件的id属性值 -->
        <div v-show="false">
            <el-table :data="tableDataExcel"
                      id="export-table"
                      stripe style="width: 100%;">
                <el-table-column label="安全帽xzsdv">
                    <template slot-scope="scope">
                        <span>{{scope.row.devId.substring(8, 18)}}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="color" label="颜色">

                </el-table-column>

                <el-table-column prop="" label="工人">
                    <template slot-scope="scope">
                        <span>{{scope.row.worker !== undefined ? scope.row.worker.name : ""}}</span>
                    </template>
                </el-table-column>

                <el-table-column prop="" label="工种">
                    <template slot-scope="scope">
                        <span>{{scope.row.profession !== undefined ? scope.row.profession.name : ""}}</span>
                    </template>
                </el-table-column>
            </el-table>
        </div>
  • 具体实现方法如下 若遇到导出的Excel文档中只有表头,没有相关数据信息,可能是因为数据渲染到DOM组件需要一定的时间,在进行导出操作时使用延时函数再进行导出功能操作。
  /**
     * 导数据时,查询所有列表集合,再进行导出操作
     */
    async function exportDataToExcel() {
        this.tableDataExcel = [];
        const result = await findAllSafeHat(0, 0, 'NORMAL', '', '');
        if (result.code === 1200) {
            this.tableDataExcel = result.data.safetyHat;
            this.exportOut();
//            setTimeout(() => {
//                this.exportOut();
//            }, 2000)
        }
    }

    function exportOut() {
        this.$confirm('导出列表数据到Excel', '提示', {
            type: 'warning',
            confirmButtonText: '确认',
            cancelButtonText: '取消'
        }).then(async () => {
            // 根据el-table组件的id属性(export-table)获取数据信息
            let wb = XLSX.utils.table_to_book(document.querySelector('#export-table'));
           
            let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'});
            try {
                FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), 'safetyHat.xlsx')
            } catch (e) {
                if (typeof console !== 'undefined') console.log(e, wbout)
            }
            return wbout;
        }).catch(() => {
            this.$message({message: '您已取消导出Excel操作!', type: 'warning'})
        });

    }
  • 结果如下

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章