ben890
ben890

Reputation: 1133

Unmerge every cell in an Excel worksheet using openpyxl

Is there a way to unmerge every cell in an Excel worksheet using openpyxl. There isn't a guarentee that every or any cell is merged, but basically I want to unmerge cells if they exist in a worksheet.

Upvotes: 3

Views: 8327

Answers (1)

sj95126
sj95126

Reputation: 6908

You can iterate through the worksheet's merged_cells attribute and use each one as an argument to unmerge_cells(). unmerge_cells() either takes the starting and ending rows and columns, or a range string, but the latter is easier to use by converting the value(s) from merged_cells to a str.

As an example:

>>> ws.merged_cells
<MultiCellRange [A2:A4 A8:D11]>

for merge in list(ws.merged_cells):
    ws.unmerge_cells(range_string=str(merge))

>>> ws.merged_cells
<MultiCellRange []>

(ws.merged_cells doesn't seem to like being iterated while you're unmerging, so list() avoids any issues)

Upvotes: 8

Related Questions