How To Set Cell Styles Using OpenPyX – Border

Method

Use the `Border` class to create a border object and apply it to a cell.

from openpyxl.styles.borders import Border,Side

Border(left=<openpyxl.styles.borders.Side object> Parameters: style=None, color=None, right=<openpyxl.styles.borders.Side object> Parameters: style=None, color=None, top=<openpyxl.styles.borders.Side object> Parameters: style=None, color=None, bottom= <openpyxl.styles.borders.Side object>

Parameters: style=None, color=None, diagonal=<openpyxl.styles.borders. Side object> Parameters: style=None, color=None, diagonal_direction=None, vertical=None, horizontal=None, diagonalUp=False, diagonalDown=False, outline= True, start=None, end=None)

Where

  • leftrighttopbottomdiagonalDefine the left, right, top, bottom, and diagonal borders, as **Side** objects.
  • diagonalDowndiagonalUpBoolean values, define the direction of the diagonal line. It can be drawn from the top-left to bottom-right, or from the bottom-left to top-right.

A Side object represents a border, which is a line-shaped graphical element. Its main properties include the line style and color. The constructor for this Side object is as follows:

Side(style=None, color=None, border_style=None)

Where

  • styleThe border style, which must be one of: “hair”“dashed”“mediumDashDot”“mediumDashDotDot”“slantDashDot”“double”“thick”“mediumDashed”“thin”“medium”“dashDotDot”“dashDot”“dotted”
  • colorThe color of the border.
  • border_styleAn alias for style.

Sample Code

#Cell Style: Setting Borders

#Import load_workbook function
from openpyxl import Workbook

#Create a new workbook
wb=Workbook()
#Get the active worksheet
ws=wb.active

#Import Border class and Side class
from openpyxl.styles import Border, Side

#Set cell borders
#Use the Border function to create individual borders
ws.cell(row=4, column=4).border = Border(left=Side(border_style='thin', \
            color='FF0000'), right=Side(border_style='thin', \
            color='FF0000'), top=Side(border_style='double', \
            color='FF0000'), bottom=Side(border_style='double', \
            color='FF0000'))

wb.save('test.xlsx')
wb.close()
Set Cell Styles Using OpenPyX - Border

Leave a Reply

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