【layUI杂记】layui之layui-excel插件的基本使用

在layui的头工具栏中加入了导出excel的功能;但是存在导出的数据会有部分失真;所以使用插件。
1、首先在layui的头工具栏中添加了导出excel的按钮
<script type="text/html" id="toolbarDemo">
	<div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
        <button class="layui-btn layui-btn-sm" lay-event="getCheckLength">获取选中数目</button>
        <button class="layui-btn layui-btn-sm" lay-event="isAll" onlick="exportfile()">导出excel</button>
    </div>
</script>
2、引用layui.min.js
<script src="${STATIC_URL}layui-excel/layui_exts/excel.min.js"></script>
3、前端处理函数
<script>
	layui.config({
		base: '${STATIC_URL}layui-excel/layui_exts/'
	}).extend({
		excels: 'excel'
	})
	
	function exportfile(){
    	layui.use(['layer'], function(){
        	var layer = layui.layer;
            var excel = layui.excel;
            
            // 请求后台
            $.ajax({
            	url: '${SITE_URL}export/excel/',
                type: 'post',
                success: function(res){
                    // 重点!!!如果后端给的数据顺序和映射关系不对,请执行梳理函数后导出
                	datas = excel.filterExportData(res.data, [
                        'indentifier_id',
                        'wbs',
                        'name',
                        'start_time',
                        'completion_time'
                    ]);
                    // 添加表头, 表头的键名顺序需要与最终导出的数据一致
                    datas.unshift({
                    	indentifier_id: '标识号',
                        wbs: 'WBS',
                        name: '工作任务',
                        start_time: '开始时间',
                        completion_time: '完成时间'
                    });
                    // 导出
                    excel.exportExcel({sheet1: datas}, '测试导出excel.xlsx', 'xlsx')
                }
            })
        })
    }
</script>
4、后台处理函数(python)
class ExportExcel(View):
    def post(self, request):
        _s = ClassName.objects.all()
        datalist = []
        for _ in _s:
            temp = {}
            temp['indentifier_id'] = _.indentifier_id
            temp['wbs'] = _.wbs
            temp['name'] = _.name
            temp['start_time'] = _.start_time
            temp['completion_time'] = _.completion_time
            datalist.append(temp)
       return JsonResponse({'code': 0, 'data': datalist, 'count': _s.count()})
posted @ 2022-04-26 14:42  郭祺迦  阅读(2411)  评论(0)    收藏  举报