Apply borders to all cells in a range with openpyxl

后端 未结 8 745
面向向阳花
面向向阳花 2021-01-03 01:28

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

8条回答
  •  清酒与你
    2021-01-03 02:02

    May be this is handy:

    from openpyxl.reader.excel import load_workbook
    from openpyxl.style import Border
    
    def set_border(ws, cell_range):
        rows = ws.range(cell_range)
        for row in rows:
            row[0].style.borders.left.border_style = Border.BORDER_THIN
            row[-1].style.borders.right.border_style = Border.BORDER_THIN
        for c in rows[0]:
            c.style.borders.top.border_style = Border.BORDER_THIN
        for c in rows[-1]:
            c.style.borders.bottom.border_style = Border.BORDER_THIN
    
    #usage example:
    ws = load_workbook('example.xlsx').get_active_sheet()
    set_broder(ws, "C3:H10")
    

    It performs reasonably fast.

提交回复
热议问题