How to use Worksheet.DisplayPageBreaks in the xlwings API way

The DisplayPageBreaks property of a Worksheet object in Excel is a Boolean value that controls whether page breaks are displayed on the worksheet. When set to True, Excel shows dotted lines indicating where pages will be divided when printed, based on current page setup settings like margins, orientation, and scaling. This is particularly useful for reviewing and adjusting print layouts before finalizing documents, ensuring content is properly distributed across pages. In xlwings, this property is accessible via the API, allowing automation of print preview adjustments directly from Python.

Syntax in xlwings:
The property can be accessed and modified using the api property of a worksheet object. The general syntax is:

worksheet.api.DisplayPageBreaks

This is a read/write property, meaning you can both retrieve its current value and set it to a new Boolean value (True or False). No parameters are required for this property, as it simply toggles the display state. Note that worksheet refers to an xlwings Sheet object, typically obtained through book.sheets['SheetName'] or book.sheets[0].

Code Examples:

  1. Check the current display status of page breaks:
import xlwings as xw
# Connect to an existing workbook or create a new one
wb = xw.Book('example.xlsx')
ws = wb.sheets['Sheet1']
# Get the current DisplayPageBreaks setting
current_setting = ws.api.DisplayPageBreaks
print(f"Page breaks are displayed: {current_setting}")

This code snippet opens an Excel file, accesses a specific worksheet, and prints whether page breaks are currently visible.

  1. Enable the display of page breaks:
import xlwings as xw
wb = xw.Book('example.xlsx')
ws = wb.sheets['Sheet1']
# Set DisplayPageBreaks to True to show page breaks
ws.api.DisplayPageBreaks = True
print("Page breaks are now visible on the worksheet.")

After running this, the worksheet will immediately show dotted page break lines in the Excel interface, assuming page breaks are defined (e.g., via manual insertion or automatic calculation based on print area).

  1. Disable the display of page breaks:
import xlwings as xw
wb = xw.Book('example.xlsx')
ws = wb.sheets['Sheet1']
# Set DisplayPageBreaks to False to hide page breaks
ws.api.DisplayPageBreaks = False
print("Page breaks are now hidden on the worksheet.")

This hides the page break lines, which can clean up the view when focusing on data entry or analysis rather than printing layout.

  1. Toggle the display based on a condition:
import xlwings as xw
wb = xw.Book('example.xlsx')
ws = wb.sheets['Sheet1']
# Toggle the current state
ws.api.DisplayPageBreaks = not ws.api.DisplayPageBreaks
print(f"Toggled display. Now set to: {ws.api.DisplayPageBreaks}")

September 18, 2026 (0)


Leave a Reply

Your email address will not be published. Required fields are marked *