Apply borders to all cells in a range with openpyxl

excel, openpyxl, python

Solution

In more pythonic way for openpyxl==3.0.5:

from openpyxl.styles import Border, Side

def set_border(ws, cell_range):
    thin = Side(border_style="thin", color="000000")
    for row in ws[cell_range]:
        for cell in row:
            cell.border = Border(top=thin, left=thin, right=thin, bottom=thin)

set_border(worksheet, 'A5:C10') 

Problem

I have a script that takes a pandas dataframe and chops it up into several hundred chunks and saves each chunk as a separate excel file. Each chunk will have the same number of columns but the number of rows varies. I've figured out how to apply all the other necessary formatting to these files with openpyxl, but I haven't yet determined the fastest way to apply borders. Also, I think I'm just not applying borders correctly, because the code below (which I suspect shouldn't need to loop over each cell individually) doesn't apply any borders. ``` from openpyxl.style import Border wb = load_workbook(filename = _fname) ws = wb.worksheets[0] for _row in ws.range('A1:L'+str(ws.get_highest_row() ) ): for _cell in _row: _cell.style.borders.left.border_style = Border.BORDER_THIN _cell.style.borders.right.border_style = Border.BORDER_THIN _cell.style.borders.top.border_style = Border.BORDER_THIN _cell.style.borders.bottom.border_style = Border.BORDER_THIN wb.save(_fname) ``` So this code works, but it doesn't apply the border I expect (the default border in excel) and it takes a lot more steps than I'd prefer. My expectation is that I should be able to do something like this: ``` from openpyxl.style import Border wb = load_workbook(filename = _fname) ws = wb.worksheets[0] _range = ws.some_range_func('A1:L'+str(ws.get_highest_row() ) ): _range.style.borders.all_borders = Borders.BORDER_THIN ``` Does this functionality exist? If not, can someone please be so kind as to at least explain how to apply the default border style and not this slightly thicker border? None of Border.BORDER_THICK, Border.BORDER_MEDIUM, Border.BORDER_THIN, or Border.BORDER_HAIR seem correct. Thanks!

Original source