簡體   English   中英

使用openpyxl模塊在python中取消合並_cell

[英]Unmerge _cell in python using openpyxl module

為什么 python openpyxl 中的 unmerge_cell 函數無法正常工作?!

 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')

出了點問題,但我不知道為什么。 我希望輸出必須是:

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

A2:B3

B4:B5

但實際輸出是:

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

 A2:B3

P/s:如果我刪除下面的代碼,那么輸出就會如我所料!。

ws.unmerge_cells(str(x))

或使用:

for x in ws.merged_cell_ranges:

取代

for x in ws.merged_cells.ranges:

然后它工作正常。 我不知道為什么。 有人可以給我解釋一下。 對不起,我的英語不好。 非常感謝!

在你的代碼中試試這個:

#######################################
#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))

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM