DEV Community


Posted on

Print Excel Documents Using Java

After finish editing an Excel document, it's inevitably that sometimes we may need to print it. And this article will introduce how to print Excel documents using Free Spire.XLS for Java.

Installation (2 Method)
1# Download the free library and unzip it, then add the Spire.Xls.jar file to your project as dependency.
2# You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

Enter fullscreen mode Exit fullscreen mode

Sample code

import com.spire.xls.Workbook;

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 PrintExcel {

    public static void main(String[] args) throws Exception{

        //Create a workbook and load an Excel file
        Workbook workbook = new Workbook();

        //Create a PrinterJob object
        PrinterJob printerJob = PrinterJob.getPrinterJob();

        //Specify printer name
        PrintService myPrintService = findPrintService("\\\\\\HP LaserJet P1007");

        //Create a PageFormat object and set it to the default size and orientation
        PageFormat pageFormat  = printerJob.defaultPage();

        //Return a copy of the Paper object associated with this PageFormat.
        Paper paper = pageFormat .getPaper();

        //Set the imageable area of this Paper.
        paper.setImageableArea(0,0,pageFormat .getWidth(),pageFormat .getHeight());

        //Set the Paper object for this PageFormat.
        pageFormat .setPaper(paper);

        //Set the number of copies
        printerJob .setCopies(1);

        //Call painter to render the pages in the specified format
        printerJob .setPrintable(workbook,pageFormat);

        //execute print
        try {
        } catch (PrinterException e) {
    //Get print service by printer name
    private static PrintService findPrintService(String printerName) {

        PrintService[] printServices = PrinterJob.lookupPrintServices();
        for (PrintService printService : printServices) {
            if (printService.getName().equals(printerName)) {
                return printService;
        return null;
Enter fullscreen mode Exit fullscreen mode

Discussion (0)