In the previous article, I introduced how to print a Word document in Java, but in this article, I would like to show you how to print an Excel worksheet in Java. Use Spire.XLS for Java in two ways: "Print with your default printer" and "Print with your specified printer".
1. From the official website of E-iceblue Free Spire. XLS for Download the free version of Java .
2. Start the IDE, create a new project, and then add the appropriate Spire. XLS.jar to the reference that was in the installed file.
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) {
//load excel.
Workbook workbook = new Workbook();
workbook.loadFromFile("test.xlsx");
//Create a PrinterJob object.
PrinterJob printerJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = printerJob.defaultPage ();
//Set the print page.
Paper paper = pageFormat.getPaper();
paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());
pageFormat.setPaper(paper);
printerJob.setCopies(1);
printerJob.setPrintable(workbook, pageFormat);
//Print.
try {
printerJob.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
}
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 { //load excel. Workbook workbook = new Workbook(); workbook.loadFromFile("test.xlsx");
//Create a PrinterJob object.
PrinterJob printerJob = PrinterJob.getPrinterJob();
//Specify the printer.
PrintService myPrintService = findPrintService("\\\\192.168.1.104\\HP LaserJet P1007");
printerJob.setPrintService( myPrintService);
PageFormat pageFormat = printerJob.defaultPage();
//Set the print page.
Paper paper = pageFormat.getPaper();
paper.setImageableArea(0, 0, pageFormat.getWidth(), pageFormat.getHeight());
pageFormat.setPaper(paper);
printerJob.setCopies(1);
printerJob.setPrintable(workbook, pageFormat);
//Print.
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;
}
<p> </p>
<p><img src="https://cdn-ak.f.st-hatena.com/images/fotolife/l/lendoris/20210114/20210114143915.png " alt="f:id:lendoris:20210114143915p:plain" title="" class="hatena-fotolife" itemprop="image" /></p>
<p><strong> </strong></p>
Recommended Posts