简体   繁体   中英

Unmerge _cell in python using openpyxl module

Why unmerge_cell function in python openpyxl does not work perpectly ?!

 import datetime
 import openpyxl
 wb = openpyxl.load_workbook('book2.xlsx')
 for ws in wb:
    for x in ws.merged_cells.ranges:
       print(x)
       ws.unmerge_cells(str(x))
 wb.save('re-book2.xlsx')

something wrong but I don't know why. I expect output must be:

[<CellRange A2:B3>, <CellRange B4:B5>]

A2:B3

B4:B5

But the actual output is:

[<CellRange A2:B3>, <CellRange B4:B5>]

 A2:B3

P/s: if I delete a below line code then the output be as i expected!.

ws.unmerge_cells(str(x))

or using:

for x in ws.merged_cell_ranges:

to replace

for x in ws.merged_cells.ranges:

then it's work fine. I dont know why. Somebody can explain to me. Sorry for my poor english. Thanks a lot!

try this in your code:

#######################################
#Iterate through all worksheets in a workbook and unmerge cells

    for sheet in wb:
        ws = wb[sheet]
        print('Now in sheet: ' + ws.title)
        # Remove merged cells
        mergedRanges=ws.merged_cells.ranges
        o=0
        while mergedRanges:
            for entry in mergedRanges:
                o=+1
                print("  unMerging: " + str(o) + ": " +str(entry))
                ws.unmerge_cells(str(entry))

#######################################

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM