关于luckysheet
luckysheet是一款在网页端实现类似excel功能的js组件,其功能相对比较丰富,配置简单而且开源。然后对于部分比较关键功能,官方api却不怎么完善,比如打印功能。
实现思路
luckysheet官方文档中,其中一个接口为getRangeHtml,该接口作用为复制指定区域内单元格的html格式数据,文档如下:
其实可以通过该方法获取对应区域内的html格式数据,然后拼接只一div中,接着打印该div内容即可。
代码实现
HTML:
<!-- 打印按钮区域-->
<div id="button-area">
<button id="print-button" onclick="to_print()">打印</button>
</div>
<!-- 打印内容区域,默认不显示,点击打印后才显示-->
<div id="print-area" style="display: none;">
<div class="noprint">
<button id="confirm-button" onclick="print()">确认打印</button>
</div>
<div id="print-html"></div>
</div>
<!-- luckysheet容器-->
<div id="luckysheet" style="margin:0px;padding:0px;position:absolute;width:100%;height:100%;left: 0px;top: 50px;"></div>
JS:
// 打印方法
// 打印时,获取luckysheet指定区域html内容,拼接至div,隐藏luckysheet容器并显示打印区域html
function to_print() {
const html = luckysheet.getRangeHtml();
document.querySelector('#print-html').innerHTML = html;
document.querySelector('#print-area').style.display = 'block';
document.querySelector('#button-area').style.display = 'none';
document.querySelector('#luckysheet').style.display = 'none';
}
CSS:
<style type="text/css" media="print">
// 隐藏打印区域按钮
.noprint {
display: none;
}
</style>
<style type="text/css">
// 合并打印区域table边框
table {
border-collapse: collapse;
}
</style>
最终效果
后记
对于以上方式实现的打印效果,实际效果并不理想,如:
- 当一个单元格内内容有多种格式时(有些字符设置为红色,有些字符设置为蓝色),实际打印时,单元格内容无法出来为空,原因为getRangeHtml无法获取到正确的html内容。
- 另外对于目标区域范围太大(宽度过大)的情况,打印出来的结果无法横向分页,导致打印效果不够理想
总体来说,以上方式只是实现了一种相对于比较简单的打印方式,寄希望于luckysheet团队早日开发官方的打印功能。
感谢luckysheet
最后感谢luckysheet团队能够带来这么优秀的产品。
附上luckysheet的gitee库地址:https://gitee.com/mengshukeji/Luckysheet