Add Page Breaks in Excel in Java
In Excel, a page break is a line divider used to separate data into different sections. It allows users to control where they want to start a new page during printing a worksheet. This article will share how to programmatically insert page breaks in an Excel worksheet using a free Java library.
Installation
To complete the task, you'll need to install Free Spire.XLS for Java library. Below are two installation methods provided.
1# Download the free library and unzip it, then add the Spire.Xls.jar file to your project as dependency.
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 insert horizontal and vertical page breaks in a worksheet easily. The complete sample code is shown as below.
import com.spire.xls.*;
public class AddPageBreaks {
public static void main(String []args) {
//Create a Workbook instance
Workbook workbook = new Workbook();
//Load an Excel file
workbook.loadFromFile("report.xlsx");
//Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
//Specify the cells where you want to add page breaks to
CellRange cell1 = sheet.getRange().get("A9");
CellRange cell2 = sheet.getRange().get("E1");
//Add a horizontal page break
sheet.getHPageBreaks().add(cell1);
//Add a vertical page break
sheet.getVPageBreaks().add(cell2);
//Set view mode to Preview in order to view the page breaks
sheet.setViewMode(ViewMode.Preview);
//Save the result file
workbook.saveToFile("ExcelPageBreaks.xlsx", ExcelVersion.Version2013);
}
}