class="MsoNormal">示例要点
本文介绍如何通过Java程序打印Excel工作表。可通过以下方法打印:
?
?
程序环境
?
?
?
Jar文件导入
方法1:手动下载jar包导入。下载jar包,并解压到指定路径,将该路径下lib文件夹下的jar文件导入java程序;
?
方法2:Maven程序中配置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>
?
完成配置后,导入jar。Eclipse中的导入方法可参考教程文档。
?
?
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; 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; 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; } }
?
?
?