How to use Range.BorderAround in the xlwings API way

The BorderAround method in the Excel object model is used to apply a border around the entire range of cells. This is particularly useful for visually distinguishing a block of data, such as a summary table or a key dataset, within a worksheet. In xlwings, this method is accessed through the api property of a Range object, which provides direct access to the underlying Excel object model. The method allows you to specify the line style, weight, and color of the border.

Syntax:
The xlwings API call follows the pattern: range.api.BorderAround(LineStyle, Weight, ColorIndex, Color)

  • LineStyle: An integer or constant from the XlLineStyle enumeration that defines the style of the border line. Common values include:
  • 1 or xlContinuous: A continuous solid line.
  • -4115 or xlDash: A dashed line.
  • -4118 or xlDot: A dotted line.
  • 4 or xlDouble: A double line.
  • Weight: An integer or constant from the XlBorderWeight enumeration that specifies the thickness of the border. Typical values are:
  • 2 or xlThin: A thin border.
  • -4138 or xlMedium: A medium border.
  • 4 or xlThick: A thick border.
  • ColorIndex: An optional integer representing a color from the current color palette. Use this or Color, but not both. If omitted, the default color (usually black) is used.
  • Color: An optional argument to specify the border color as an RGB value. This can be provided as an integer (e.g., 0xFF0000 for red) or using the RGB function from the Excel object model via xlwings. If both ColorIndex and Color are omitted, the default color applies.

Example:
Here is an xlwings code example that demonstrates the use of BorderAround. First, ensure you have xlwings installed and an Excel application running.

import xlwings as xw

# Connect to the active Excel instance and get the active sheet
app = xw.apps.active
wb = app.books.active
sheet = wb.sheets.active

# Define a range, e.g., A1:D10
target_range = sheet.range('A1:D10')

# Apply a thick, continuous red border around the range
# Using Color as an RGB integer for red (0xFF0000)
target_range.api.BorderAround(LineStyle=1, Weight=4, Color=0xFF0000)

# Alternatively, use constants from the Excel enumeration for clarity
# First, import the constants (optional, as you can use numeric values)
from xlwings.constants import LineStyle, BorderWeight
target_range.api.BorderAround(LineStyle=LineStyle.xlContinuous,
Weight=BorderWeight.xlThick,
Color=0x0000FF) # Blue border

# Another example with a dashed medium border using default color
target_range.api.BorderAround(LineStyle=-4115, Weight=-4138)

# Save the workbook if needed
wb.save('output_with_borders.xlsx')

October 15, 2026 (0)


Leave a Reply

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