layui-excel扩展导出的文件可用office打开,正常显示;直接用table带的导出功能,导出的文件用office打开显示乱码。
layui-excel扩展下载地址:https://fly.layui.com/extend/excel/
1 @extends('Admin.common.title') 2 @section('content') 3 4 <button class="layui-btn layui-btn-warm" type="button" id="download">下载数据卡</button> 5 6 <!-- 导出表 不展示 --> 7 <div style="display:none;"><table id="data_export"></table></div> 8 9 <script> 10 layui.config({base: '/static/layui-excel/layui_exts/'}).use(['table', 'form', 'laydate', 'excel'], function () { 11 var form = layui.form; 12 var table = layui.table; 13 var laydate = layui.laydate; 14 var excel = layui.excel; 15 16 //监听下载按钮 17 $("#download").click(function () { 18 var ins1=table.render({ 19 elem: '#data_export' 20 ,url:'/Shop/list' 21 ,method:'POST' 22 ,headers: { 23 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') 24 } 25 ,async: false 26 ,cols: [[ 27 {field:'brand', title: '品牌'} 28 ,{field:'year', title: '年份'} 29 ,{field:'activity', title: '活动'} 30 ,{field:'stage', title: '阶段'} 31 ,{field:'start_date', title: '日期'} 32 ]] 33 ,page: false 34 ,limit: Number.MAX_VALUE 35 ,done: function (res, curr, count) { 36 exportFile('data_export') 37 } 38 }); 39 }) 40 //表格导出 41 function exportFile(id) { 42 //根据传入tableID获取表头 43 var headers = $("div[lay-id=" + id + "] .layui-table-box table").get(0); 44 var htrs = Array.from(headers.querySelectorAll('tr')); 45 var titles = {}; 46 for (var j = 0; j < htrs.length; j++) { 47 var hths = Array.from(htrs[j].querySelectorAll("th")); 48 for (var i = 0; i < hths.length; i++) { 49 var clazz = hths[i].getAttributeNode('class').value; 50 if (clazz != ' layui-table-col-special' && clazz != 'layui-hide') { 51 //排除居左、具有、隐藏字段 52 //修改:默认字段data-field+i,兼容部分数据表格中不存在data-field值的问题 53 titles['data-field' + i] = hths[i].innerText; 54 } 55 } 56 } 57 //根据传入tableID获取table内容 58 var bodys = $("div[lay-id=" + id + "] .layui-table-box table").get(1); 59 var btrs = Array.from(bodys.querySelectorAll("tr")) 60 var bodysArr = new Array(); 61 for (var j = 0; j < btrs.length; j++) { 62 var contents = {}; 63 var btds = Array.from(btrs[j].querySelectorAll("td")); 64 for (var i = 0; i < btds.length; i++) { 65 for (var key in titles) { 66 //修改:默认字段data-field+i,兼容部分数据表格中不存在data-field值的问题 67 var field = 'data-field' + i; 68 if (field === key) { 69 //根据表头字段获取table内容字段 70 contents[field] = btds[i].innerText; 71 } 72 } 73 } 74 bodysArr.push(contents) 75 } 76 //将标题行置顶添加到数组 77 bodysArr.unshift(titles); 78 //导出excel 79 excel.exportExcel({ 80 sheet1: bodysArr 81 }, 'download-filename' + new Date().toLocaleString() + '.xlsx', 'xlsx'); 82 } 83 }); 84 </script> 85 @endsection