Losing merged cells border while editing Excel file with openpyxl

后端 未结 5 1393
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-09 13:22

I have two sheets in an Excel file and the first one is a cover sheet which I don\'t need to edit. There are a few merged cells in the cover sheet, and when I edit the file usin

5条回答
  •  盖世英雄少女心
    2021-02-09 14:17

    If you are using openpyxl 2.4, the solution offered by micki_mouse may not work. I managed to make it work by tweaking it this way:

    from openpyxl import load_workbook
    from openpyxl.utils import range_boundaries
    
    wb = load_workbook(template_path)
    ws = wb.active
    for merged_cells in ws.merged_cell_ranges:
        min_col, min_row, max_col, max_row = range_boundaries(merged_cells)
        style = ws.cell(row=min_row, column=min_col)._style
        for col in range(min_col, max_col + 1):
            for row in range(min_row, max_row + 1):
            ws.cell(row=row, column=col)._style = style
    

    Basically, you have to use "merged_cell_ranges" (deprecated in 2.5.0-b1) to correctly access the merged cells within the worksheet. You also must specify explicitely in the cell constructor the row and column

提交回复
热议问题