Losing merged cells border while editing Excel file with openpyxl

2024/10/2 22:22:06

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 using openpyxl, without even touching the cover sheet, I lose borders from the merged cells. I am using load_workbook('excel file') to load the Excel file and saving it with a different filename.

Is there any way to fix this problem?

Answer

Actual solution is to patch the libraries code by including this snippet after including the library, it fixes the problem. (Note: don't worry about missing definitions, e.g. COORD_RE, i.e. the patch is self-contained)

from itertools import product
import types
import openpyxl
from openpyxl import worksheet
from openpyxl.utils import range_boundariesdef patch_worksheet():"""This monkeypatches Worksheet.merge_cells to remove cell deletion bughttps://bitbucket.org/openpyxl/openpyxl/issues/365/styling-merged-cells-isnt-workingThank you to Sergey Pikhovkin for the fix"""def merge_cells(self, range_string=None, start_row=None, start_column=None, end_row=None, end_column=None):""" Set merge on a cell range.  Range is a cell range (e.g. A1:E1)This is monkeypatched to remove cell deletion bughttps://bitbucket.org/openpyxl/openpyxl/issues/365/styling-merged-cells-isnt-working"""if not range_string and not all((start_row, start_column, end_row, end_column)):msg = "You have to provide a value either for 'coordinate' or for\'start_row', 'start_column', 'end_row' *and* 'end_column'"raise ValueError(msg)elif not range_string:range_string = '%s%s:%s%s' % (get_column_letter(start_column),start_row,get_column_letter(end_column),end_row)elif ":" not in range_string:if COORD_RE.match(range_string):return  # Single cell, do nothingraise ValueError("Range must be a cell range (e.g. A1:E1)")else:range_string = range_string.replace('$', '')if range_string not in self._merged_cells:self._merged_cells.append(range_string)# The following is removed by this monkeypatch:# min_col, min_row, max_col, max_row = range_boundaries(range_string)# rows = range(min_row, max_row+1)# cols = range(min_col, max_col+1)# cells = product(rows, cols)# all but the top-left cell are removed#for c in islice(cells, 1, None):#if c in self._cells:#del self._cells[c]# Apply monkey patchworksheet.Worksheet.merge_cells = merge_cells
patch_worksheet()

Source https://bitbucket.org/openpyxl/openpyxl/issues/365/styling-merged-cells-isnt-working

https://en.xdnf.cn/q/70802.html

Related Q&A

Reset CollectorRegistry of Prometheus lib after each unit test

I have a class A that initializes a Counter in its initfrom prometheus_client import Counter class A:def __init__(self):self.my_counter = Counter(an_awesome_counter)def method_1(self):return 1def metho…

Why does Django ORM allow me to omit parameters for NOT NULL fields when creating an object?

Stupid question time. I seem to be able to create an object for a Django model even though I omit a column that was defined as NOT NULL and I dont understand why. Heres my model:class Movie(models.Mo…

Where should i do the django validations for objects and fields?

Im creating a django application which uses both the Django Rest Framework and the plain django-views as entrypoint for users.I want to do validation both independant fields of my models, and on object…

Why does bytes.fromhex() treat some hex values strangely?

Im trying to use the socket library in Python to send bytes of two hex digits to a piece of hardware programmed to accept them. To create the bytes from a user-entered string of hex digits, Im trying …

Extracting beats out of MP3 music with Python

What kind of solutions are there to analyze beats out of MP3 music in Python? The purpose of this would be to use rhythm information to time the keyframes of generated animation, export animation as v…

Switch to popup in python using selenium

How do I switch to a popup window in the below selenium program. Ive looked up for all possible solutions but havent been able to get my head around them. Please help!!from selenium import webdriver fr…

Segmentation fault while redirecting sys.stdout to Tkinter.Text widget

Im in the process of building a GUI-based application with Python/Tkinter that builds on top of the existing Python bdb module. In this application, I want to silence all stdout/stderr from the consol…

Why do pandas and dask perform better when importing from CSV compared to HDF5?

I am working with a system that currently operates with large (>5GB) .csv files. To increase performance, I am testing (A) different methods to create dataframes from disk (pandas VS dask) as well a…

is there any pool for ThreadingMixIn and ForkingMixIn for SocketServer?

I was trying to make an http proxy using BaseHttpServer which is based on SocketServer which got 2 asynchronous Mixins (ThreadingMixIn and ForkingMixIn)the problem with those two that they work on each…

Python - Read data from netCDF file with time as seconds since beginning of measurement

I need to extract values from a netCDf file. I am pretty new to python and even newer this file format. I need to extract time series data at a specific location (lat, lon). I have found that there is …