目录

前端点击按钮打印Excel

前端点击按钮打印Excel

前端点击按钮打印Excel

实现思路

太长不看版

后端spire.xls将excel转为html,前端打印iframe

具体说明

前端只能打印html文档已有的dom节点,无法直接打印Excel,那么可以将Excel转换为html,在iframe中将html渲染出来,最后js调用打印接口就可以了。而转换这一步可以放在后端操作,实现工具库是 spire.xls ,pom看下面代码。

效果还可以 🍕

https://i-blog.csdnimg.cn/blog_migrate/e3d31a490afcd3868b4635c2e050c4e6.png

代码

后端

  • pom
<dependency>
	<groupId>e-iceblue</groupId>
	<artifactId>spire.xls</artifactId>
	<version>3.12.3</version>
</dependency>

<repository>
	<id>com.e-iceblue</id>
	<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
// 读取Excel
Workbook wb = new Workbook();
String excelFileName = "xxx/xx.xlsx";
wb.loadFromFile(excelFileName);
// 获取Excel的第一张表
Worksheet sheet = wb.getWorksheets().get(0);
// 删除空白
for (int i = sheet.getLastRow(); i >= 1; i--) {
    if (sheet.getRows()[i - 1].isBlank()) {
        sheet.deleteRow(i);
    }
}

for (int j = sheet.getLastColumn(); j >= 1; j--) {
    if (sheet.getColumns()[j - 1].isBlank()) {
        sheet.deleteColumn(j);
    }
}

// 另保存为html
String htmlFileName = "yyy/yy.html";
sheet.saveToHtml(htmlFileName);

前端

// content 是从后端拿到的html文档字符串
export function printIframe(content) {
  let iframe = document.createElement('iframe')
  iframe.id = new Date().getTime()
  iframe.width = '1200'
  // 高度看情况设定
  iframe.height = '60000'
  iframe.style.display = 'none'
  document.body.appendChild(iframe)
  iframe.contentWindow.document.write(content)
  // 移除spire.xls转换时添加在页面顶部的水印
  let watermark = iframe.contentWindow.document.querySelector('body > h2')
  iframe.contentWindow.document.body.removeChild(watermark)
  iframe.contentWindow.print()

  // 移除iframe
  setTimeout(() => {
    document.body.removeChild(document.getElementById(iframe.id))
  }, 5000)
}

参考博客