Set Page Margins in Excel in Java

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

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);

}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store