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 theXlLineStyleenumeration that defines the style of the border line. Common values include:1orxlContinuous: A continuous solid line.-4115orxlDash: A dashed line.-4118orxlDot: A dotted line.4orxlDouble: A double line.Weight: An integer or constant from theXlBorderWeightenumeration that specifies the thickness of the border. Typical values are:2orxlThin: A thin border.-4138orxlMedium: A medium border.4orxlThick: A thick border.ColorIndex: An optional integer representing a color from the current color palette. Use this orColor, 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.,0xFF0000for red) or using theRGBfunction from the Excel object model viaxlwings. If bothColorIndexandColorare 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')
Leave a Reply