Set Page Margins in Excel in Java

·

2 min read

In Excel, page margins are the white space between the worksheet data and the left, right, top, and bottom edges of the printed page. This article will share how to programmatically set Excel page margins before printing an Excel worksheets using Free Spire.XLS for Java.

Installation (2 methods)

Method 1: Download the free library and unzip it. Then add the Spire.Office.jar file to your project as dependency.

Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>5.1.0</version>
    </dependency>
</dependencies>

Sample Code

Free Spire.XLS for Java allows you to set top margin, bottom margin, left margin, right margin, header margin, and footer margin. Please note that the unit for margin is inch on Free Spire.XLS for Java while On Microsoft Excel, it is cm (1 inch=2.54 cm).

import com.spire.xls.*;

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

        //Load the sample document from file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Test.xlsx");

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

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

        //Set the page margins of bottom, left, right and top.
        pageSetup.setBottomMargin(2);
        pageSetup.setLeftMargin(1);
        pageSetup.setRightMargin(1);
        pageSetup.setTopMargin(3);

        //Set the margins of header and footer.
        pageSetup.setHeaderMarginInch(2);
        pageSetup.setFooterMarginInch(2);

        //Save to file.
        workbook.saveToFile("setMarginsOfExcel.xlsx", ExcelVersion.Version2013);

    }
}

ExcelMargin.jpg