pythonexcelopenpyxl

Apply outline border only to range of cells with openpyxl


I'm looking to apply an outline border to a range of cells using openpyxl.

I've seen articles describing how to iterate over cells in a range & apply a border to each cell - this is not what I need.

Below is my code to define the border, but I cannot see how to apply it to a range/selection of cells.

thickBorder = openpyxl.styles.borders.Border(left=openpyxl.styles.borders.Side(style="thick"),
                                           right=openpyxl.styles.borders.Side(style="thick"),
                                           top=openpyxl.styles.borders.Side(style="thick"),
                                           bottom=openpyxl.styles.borders.Side(style="thick"),
                                           outline=True
                                           )

I've also tried adding a border to a range, but this doesn't work.

myRange = ws["B4":"Y6"]
myRange.border = thickBorder

Any suggestions?


Solution

  • From this answer

    You can do operations over a range of cells using the cell_rangemodule (from the worksheet module).

    A CellRange object has a few useful properties you can leverage to do what you want:

    from openpyxl.worksheet.cell_range import CellRange
    import openpyxl.styles.borders import Border, Side
    
    range = CellRange("B4:Y6")
    for row, col in range.cells:
        top = Side(style="thick") if (row, col) in range.top else None
        left = Side(style="thick") if (row, col) in range.left else None
        right = Side(style="thick") if (row, col) in range.right else None
        bottom = Side(style="thick") if (row, col) in range.bottom else None
        ws.cell(row, col).border = bd.Border(left, right, top, bottom, outline=True)