为什么 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))
#######################################
