配置pom.xml文件
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>3.11.2</version>
</dependency>
</dependencies>
Java代码
1. 默认打印机打印
import com.spire.xls.*;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
//java项目 www.fhadmin.org
public class Print {
public static void main(String[] args) {
//加载excel工作簿
Workbook workbook = new Workbook();
workbook.loadFromFile("test.xlsx");
//创建 PrinterJob对象
PrinterJob printerJob = PrinterJob.getPrinterJob();
//指定打印页面为默认大小和方向
PageFormat pageFormat = printerJob.defaultPage();
//设置相关打印选项
Paper paper = pageFormat.getPaper();
paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());
pageFormat.setPaper(paper);
printerJob.setCopies(1);
printerJob.setPrintable(workbook, pageFormat);
//执行打印
try {
printerJob.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
}
2. 指定打印机打印
import com.spire.xls.*;
import javax.print.PrintService;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
//java项目 www.fhadmin.org
public class Print {
public static void main(String[] args) throws Exception {
//加载excel工作表
Workbook workbook = new Workbook();
workbook.loadFromFile("test.xlsx");
//创建 PrinterJob对象
PrinterJob printerJob = PrinterJob.getPrinterJob();
//指定打印机
PrintService myPrintService = findPrintService("\\\\192.168.1.104\\HP LaserJet P1007");
printerJob.setPrintService( myPrintService);
//指定打印页面为默认大小和方向
PageFormat pageFormat = printerJob.defaultPage();
//设置相关打印选项
Paper paper = pageFormat.getPaper();
paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());
pageFormat.setPaper(paper);
printerJob.setCopies(1);
printerJob.setPrintable(workbook, pageFormat);
//执行打印
try {
printerJob.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
//通过打印机名称获取打印服务
private static PrintService findPrintService(String printerName) {
PrintService[] printServices = PrinterJob.lookupPrintServices();
for (PrintService printService : printServices) {
if (printService.getName().equals(printerName)) {
return printService;
}
}
return null;
}
}