本文介绍如何使用spire.xls for java 打印excel工作表。可通过默认打印机打印,也可以指定打印机打印。
默认打印机打印
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();
}
}
}
指定打印机打印
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;
}
}