使用easyExcel导出excel文件

1.导入jar包


            com.alibaba
            easyexcel
            3.0.5

2.点击导出按钮,浏览器开始下载对应的数据,也可以实现批量导出

3.实现思路:利用layui table监听点击事件,把点击的数据获取到,遍历拿到数据的id,难点就是

怎么样获取选中的数据,解决办法:将table提升为全局变量,后续使用就可以直接使用,很重要!

var table;

    layui.use(['table','form'], function(){
        table = layui.table;
        var form = layui.form;

        tableIns=table.render({
            id:'id',
            elem: '#partyMemberList',
            url:"/partyMember/selectPartyMember",
            method: 'get', //默认:get请求
            cellMinWidth: 80,
            page: true,
            request: {
                pageName: 'pageNum', //页码的参数名称,默认:pageNum
                limitName: 'pageSize' //每页数据量的参数名,默认:pageSize
            },
            response:{
                statusName: 'code', //数据状态的字段名称,默认:code
                statusCode: 200, //成功的状态码,默认:0
                countName: 'totals', //数据总数的字段名称,默认:count
                dataName: 'list' //数据列表的字段名称,默认:data
            },
            cols: [[{type: "checkbox"},
                {type:'numbers'/*,width:"5%"*/}
                ,{field:'name', title:'姓名',align:'center'/*,width:"10%"*/}
                ,{field:'sex', title:'性别',align:'center'/*,width:"10%"*/}
                ,{field:'age', title:'年龄',align:'center'/*,width:"15%"*/}
                ,{field:'phone', title:'手机号',align:'center'/*,width:"10%"*/}
                ,{field:'degree', title:'学历',align:'center'/*,width:"10%"*/}
                ,{fixed:'right',title:'操作',align:'center', toolbar:'#optBar'/*,width:"25%"*/}
            ]],
            done: function(res, curr, count){
               console.log("res:",res)
                pageCurr=curr;

            }

        });
function exportParty(){
    var checkStatus = table.checkStatus('id');
    var data=checkStatus.data;

    $.each(data,function(index,item){
        ids.push(item.id);
    });
    console.log("ex:",ids)
    downloadFileWithUrl("/partyMember/exportParty/?ids=" + ids.join(","));

    console.log("url:","/partyMember/exportParty/?ids=" + ids.join(","))
    //清空ids
    ids=[];
}

4.拿到id后怎样向后端传输这个id也是一个问题,解决办法是:利用a标签进行传输,将id数据转化成string拼接到url后面

function downloadFileWithUrl(url){
    var elink = document.createElement("a");
    elink.style.display = "none";
    elink.href = url;
    elink.click();

}

5.后端代码,拿到id后把对应的数据查询到,使用ExcelUtils导出方法就可以实现导出功能

 @Override
    public String exportParty(List ids,HttpServletResponse response) throws Exception {
        List partyMembers = new ArrayList<>();
        String sheetName="党员管理";
        String excelName="党员管理";
        if(ids.size()==0){
            partyMembers=partyMemberMapper.selectAll();
        }else {
            for (Integer id:ids){
                PartyMember partyMember = partyMemberMapper.selectById(id);
                partyMembers.add(partyMember);
            }
        }


        ExcelUtils.export2Web(response, excelName,sheetName, PartyMember.class,partyMembers );
    return "导出成功";
    }

 

你可能感兴趣的:(java)