layui的table自带导出excel的toolbar,但这个table的导出功能仅限于动态的表格。有时候我们需要用到静态表格,比如:
</table class="layui-table" id="showdata">
<thead>
<tr>
<th></th>
<th>完成日期</th>
<th>物料代码</th>
<th>名称</th>
<th>批号</th>
<th>检验人</th>
<th>检验结果</th>
<th>检验结论</th>
<th> </th></tr> </thead><tbody>
<tr><td>1</td>
<td>2022-12-02</td>
<td>22716</td>
<td>71试剂盒</td>
<td>2207123</td>
<td>检验1</td>
<td>CV差异依旧较大</td>
<td>不合格</td>
<td><a href="read.php?m=51&id=829" target="_blank" title="查看详情">查看详情</a></td>
</tr>
<tr>
<td>2</td>
<td>2022-12-05</td>
<td>K111</td>
<td>11试剂盒</td>
<td>211125</td>
<td>检验2</td>
<td></td>
<td>合格</td>
<td><a href="read.php?m=51&id=847" target="_blank" title="查看详情">查看详情</a></td>
</tr>
</tbody>
</table>
对于这类表格(有明显的thread和tbody),可以先用jquery获得th和各行的td内数据,主要需要排除的单元格要对应,不然表格容易出乱,然后引用layui(layer)自带的导出模块exportFile,具体代码如下:
layui.use(['element','table'], function(){
var $ = layui.jquery
,table = layui.table
,layer = layui.layer;
$("#btnExport").click(function (){
var tharr=[],trarr=[];
var th=$("#showdata thead").find('th');
for (i=1;i<th.length-1;i++ ){
tharr.push(th[i].innerText);
}
$('#showdata tbody tr').each(function() {
var tds = $(this).find("td");
var tdarr=[];
for (i=1;i<tds.length-1;i++ ){
tdarr.push(tds[i].innerText);
}
trarr.push(tdarr);
});
table.exportFile(
tharr,trarr,'检验数据.xls');
});
});
记得在合适的位置添加触发的导出按钮
<div style="text-align: right;">
<button type="button" id="btnExport" class="layui-btn layui-btn-primary layui-btn-sm">
<i class="layui-icon layui-icon-export"></i>
</button></div>
Comments | NOTHING