elementUI 将el-table表格导出excel文件

单机
1 首先安装依赖:xlsx、file-saver:
npm install xlsx --save
npm install file-saver --save
2在main.js中导入

// vue中导出excel表格模板
import FileSaver from 'file-saver'
import XLSX from 'xlsx'

Vue.prototype.$FileSaver = FileSaver; //设置全局
Vue.prototype.$XLSX = XLSX; //设置全局

2点击导出按钮

 <el-button @click="$router.push('/addressAdd')" type="primary" icon="el-icon-edit" >添加地址</el-button>
        <el-button @click="exportToExcel">导出</el-button>
<el-table
                    id="out-table"
                    ref="multipleTable"
                    :data="tableData"
                    :header-cell-style="{background:'#ccc',color: ' #333'}"
                    :show-header="true"
                    style="width: 100%"
                    :highlightCurrentRow="true"
            >
            <el-table-column prop="id" label="编号"></el-table-column>

            <el-table-column prop="member_id" label="会员id"></el-table-column>

            <el-table-column prop="receive_name" label="收货人姓名">
            </el-table-column>

            <el-table-column prop="tel" label="电话">
            </el-table-column>

            <el-table-column prop="poscode" label="邮编">
            </el-table-column>

            <el-table-column prop="addmes" label="省市区/县">
            </el-table-column>

            <el-table-column prop="detail_address" label="详细地址">
            </el-table-column>


            <!--fixed="right"-->
            <el-table-column
                    label="操作">
                <template slot-scope="scope">
                    <el-button @click="edit(scope.row)" type="text" size="small">修改</el-button>
                    <el-button @click="deleteAddressVip(scope.row)" type="text" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

3在组件的methods中写入方法

methods: {
            //   点击按钮  导出excel表格:
            exportToExcel: function() {
                let tables = document.getElementById("out-table");
                let table_book = this.$XLSX.utils.table_to_book(tables);
                var table_write = this.$XLSX.write(table_book, {
                    bookType: "xlsx",
                    bookSST: true,
                    type: "array"
                });
                try {
                    this.$FileSaver.saveAs(
                        new Blob([table_write], { type: "application/octet-stream" }),
                        "sheetjs.xlsx"
                    );
                } catch (e) {
                    if (typeof console !== "undefined") console.log(e, table_write);
                }
                return table_write;
            },
            }

4注意:

this.$XLSX.utils.table_to_book中放的是table的dom节点
sheetjs.xlsx导出的是表格的名字

Logo

前往低代码交流专区

更多推荐