DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

Print Excel Documents in Java

Printing Excel documents from java code is a common requirement for java developers. In this article, I am going to introduce how to print an Excel document and set all kinds of print settings by using Free Spire.XLS for Java.

There are two important classes involved in printing, namely PrinterJob class and PageSetup class. Check below table to learn about their definitions.

Class Definition Package
PrinterJob The PrinterJob class is the principal class that controls printing. An application calls methods in this class to set up a job, optionally to invoke a print dialog with the user, and then to print the pages of the job. java.awt.print
PageSetup Represents the page setup description. The PageSetup object contains all page setup attributes (left margin, bottom margin, paper size, and so on) as properties. It also contains print settings attributes like print area, print quality, print comments, etc. com.spire.xls.Worksheet

Installing Spire.Xls.jar

If you create a Maven project, you can easily import the jar in your application using the following configurations. For non-Maven projects, download the jar file from this link and add it as a dependency in your application.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId> e-iceblue </groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>3.9.1</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Example 1. Print with default printer

import com.spire.xls.Workbook;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PrintByDefaultPrinter {
    public static void main(String[] args) {

        //Create a workbook and load an Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");

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

        //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 number of copies
        printerJob.setCopies(1);

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

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

        //Execute print
        try {
            printerJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Example 2. Print with the specific printer

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();
        workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");

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

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

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

        //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 {
            printerJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
    //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

Example 3. Set print settings through PageSetup object

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

    public static void main(String[] args) {

        //Create a workbook and load an Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.xlsx");

        //Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        //Get the PageSetup object
        PageSetup pageSetup = worksheet.getPageSetup();

        //Specify the print area
        pageSetup.setPrintArea("A1:E19");

        //Set row 1 as the title row, which means row 1 will be printed repeatedly at the top of each page
        pageSetup.setPrintTitleRows("$1:$1");

        //Allow to print grid lines
        pageSetup.isPrintGridlines(true);

        //Allow to print headings
        pageSetup.isPrintHeadings(true);

        //Allow to print worksheet in black & white mode
        pageSetup.setBlackAndWhite(true);

        //Set print quality
        pageSetup.setPrintQuality(150);

        //Set the order that Microsoft Excel uses to number pages when printing a large worksheet
        pageSetup.setOrder(OrderType.OverThenDown);

        //Print document through PrinterJob interface
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        PageFormat pageFormat  = printerJob.defaultPage();
        Paper paper = pageFormat.getPaper();
        paper.setImageableArea(0,0,pageFormat.getWidth(),pageFormat.getHeight());
        printerJob.setCopies(1);
        pageFormat.setPaper(paper);
        printerJob.setPrintable(workbook,pageFormat);
        try {
            printerJob.print();
        } catch (PrinterException e) {
            e.printStackTrace();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)