layui导出表格全部数据

尚
转载
2019-11-18 17:12:59 8955浏览

layui(谐音:类UI) 是一款采用自身模块规范编写的前端 UI 框架,遵循原生 HTML/CSS/JS 的书写与组织形式,门槛极低,拿来即用。

layui自带的导出表格,只能导出当前页面,如果当前页包含全部数据,那不就是导出全部数据了吗,所以我给导出事件单独定义了一个请求,当触发这个请求时,在后台查询数据时不要按接收的page 和 limit查询,而是查询全部,这样就实现了导出全部数据。

页面代码:

<!--导出按钮 或其他触发事件-->
<button class="export">导出报表</button>

<!--导出表 不展示-->
<div style="display: none;">
    <table id="data_export">
    </table>
</div>
layui.use(['form', 'table', 'layer'], function () {
        var table = layui.table,
            form = layui.form,
            layer = layui.layer;
        //导出表格
        var ins1 = table.render({
            elem: '#data_export',
            url: "url", //数据接口
            method: 'post',
            title: '导出表的表名',
            where: {
                mycode: "all"
            },
            limit: 10,
            cols: [[
                {field: 'id', title: 'ID'},
                {field: 'name', title: '名称'},
            ]],
            done: function (res, curr, count) {
                exportData = res.data;
            }
        });
        //导出按钮
        $(".export").click(function () {
            table.exportFile(ins1.config.id, exportData, 'xls');
        });
    })

后台处理:

if ($mycode) {    $data = M('mysql')->where($where)->select();  
    echo json_encode(['code' => 0, 'msg' => "", 'data' => $data]);                     
}

优化:对应的代码是上面第二段js代码:

//导出改为单独的事件,每次点击导出才会执行
    $(".export").click(function(){
        var ins1=table.render({
            elem: '#data_export',
            url: "url", //数据接口
            method: 'post',
            title: '表名',
            where: {
                mycode: "all"
            },
            limit: 10,
            cols: [[
                {field: 'id', title: 'ID'},
                {field: 'name', title: '名字'},
            ]],
            done: function (res, curr, count) {
                exportData=res.data;
                table.exportFile(ins1.config.id,exportData, 'xls');
            }
        });
    })

其实就是把 table.exportFile(ins1.config.id,exportData, 'xls'); 放到了done中,虽然看起来改的不多,但是本质已经变了,之前的方式是进入页面就加载隐藏的导出表。

而现在是点击导出的时候才会渲染隐藏导出表,在导出表内容多的时候,导出速度慢点用户会觉得是合理的,比页面加载速度慢要好多了。

更多layui相关知识请关注layui框架

以上就是layui导出表格全部数据的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:博客园,如有侵犯,请联系admin@php.cn删除