How to use Application.DefaultSheetDirection in the xlwings API way

The Application.DefaultSheetDirection property in Excel’s object model allows developers to set or retrieve the default direction in which new worksheets are laid out within a workbook. This property influences whether the sheet content is displayed from left-to-right (typical for languages like English) or right-to-left (common for languages such as Arabic or Hebrew). It is particularly useful in internationalized applications where the user interface must adapt to different reading orientations. In xlwings, this property can be accessed and modified through the api property of the App object, providing a programmatic way to control sheet direction directly from Python.

Syntax in xlwings:

app.api.DefaultSheetDirection

This property is both readable and writable. It accepts integer values that correspond to specific direction settings:

  • xlLTR (value: -5003): Sets the default direction to left-to-right.
  • xlRTL (value: -5004): Sets the default direction to right-to-left.

These constants are part of the Excel enumeration XlSheetDirection. In xlwings, you can use the integer values directly or import the constants from the win32com.client.constants module if working on Windows with COM support, though xlwings typically abstracts this. The property applies at the application level, meaning it affects all new workbooks and sheets created during the session until changed.

Code Examples:

  1. Reading the Current Default Sheet Direction:
import xlwings as xw
app = xw.App(visible=False)
current_direction = app.api.DefaultSheetDirection
print(f"Default sheet direction: {current_direction}") # Output: -5003 for left-to-right
app.quit()

This example retrieves the current setting, which defaults to left-to-right in most installations.

  1. Setting the Default Sheet Direction to Right-to-Left:
import xlwings as xw
app = xw.App(visible=False)
app.api.DefaultSheetDirection = -5004 # xlRTL for right-to-left
# Create a new workbook to see the effect
wb = app.books.add()
ws = wb.sheets[0]
print(f"New sheet direction set to: {app.api.DefaultSheetDirection}")
wb.save('right_to_left_sheet.xlsx')
app.quit()

After setting the property, any new worksheets will adopt the right-to-left layout, affecting text alignment and sheet navigation.

  1. Toggling Between Directions Based on User Input:
import xlwings as xw
def set_sheet_direction(direction='LTR'):
app = xw.App(visible=False)
if direction.upper() == 'RTL':
    app.api.DefaultSheetDirection = -5004
else:
    app.api.DefaultSheetDirection = -5003
    wb = app.books.add()
    print(f"Sheet direction configured for {direction}.")
app.quit()
set_sheet_direction('RTL')

May 20, 2026 (0)


Leave a Reply

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