Losing merged cells border while editing Excel file with openpyxl

后端 未结 5 1395
佛祖请我去吃肉
佛祖请我去吃肉 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:26

    I know this is old but I got the same issue and the patch didn't work for me so I found a work around by using the function in the documentation that adds a style for merged cells and then looping on all the merged cells and calling the function on each range

    from openpyxl import load_workbook
    from openpyxl.styles import Border, Side, PatternFill, Font, GradientFill, 
    Alignment
    
    def style_range(ws, cell_range, border=Border(), fill=None, font=None, 
    alignment=None):
        """
        Apply styles to a range of cells as if they were a single cell.
    
        :param ws:  Excel worksheet instance
        :param range: An excel range to style (e.g. A1:F20)
        :param border: An openpyxl Border
        :param fill: An openpyxl PatternFill or GradientFill
        :param font: An openpyxl Font object
        """
    
        top = Border(top=border.top)
        left = Border(left=border.left)
        right = Border(right=border.right)
        bottom = Border(bottom=border.bottom)
    
        first_cell = ws[cell_range.split(":")[0]]
        if alignment:
            ws.merge_cells(cell_range)
            first_cell.alignment = alignment
    
        rows = ws[cell_range]
        if font:
            first_cell.font = font
    
        for cell in rows[0]:
            cell.border = cell.border + top
        for cell in rows[-1]:
            cell.border = cell.border + bottom
    
        for row in rows:
            l = row[0]
            r = row[-1]
            l.border = l.border + left
            r.border = r.border + right
            if fill:
                for c in row:
                    c.fill = fill
    
    file = 'file.xlsx'
    
    wb = load_workbook(file)
    ws = wb['Table 1']
    
    thin = Side(border_style="thin", color="000000")
    border = Border(top=thin, left=thin, right=thin, bottom=thin)
    
    for range in ws.merged_cells.ranges:
        style_range(ws, str(range), border=border)
    
    wb.save('newExcel.xlsx')
    

提交回复
热议问题