openpyxl遍历所有行并取消合并单元格

时间:2020-05-20 13:34:45

标签: python-3.x excel openpyxl

我需要取消合并页面上所有合并的单元格。

我的代码

merged_cell_coord = []
for range_ in sheet.merged_cell_ranges:
    # get current coordinate from all merget cell and set it as a string
    merged_cell_coord.append(range_.__str__())
for i in (merged_cell_coord):
    sheet.unmerge_cells(i)

print(merged_cell_coord)给我一个字符串列表

['E1083:G1083', 'E742:G742', 'E864:G864', 'E919:G919', 'E950:G950', 'E951:G951', 'E1033:G1033', 'E689:G689', 'E519:G519', 'E520:G520', 'E544:G544', 'E568:G568', 'E569:G569', 'E590:G590', 'E617:G617', 'E618:G618', 'E645:G645', 'E676:G676', 'E688:G688', 'E509:G509', 'E305:G305', 'E324:G324', 'E348:G348', 'E349:G349', 'E371:G371', 'E375:G375', 'E381:G381', 'E382:G382', 'E410:G410', 'E465:G465', 'E497:G497', 'E256:G256', 'H1:O1', 'E4:G4', 'E5:G5', 'E45:G45', 'E91:G91', 'E111:G111', 'E128:G128', 'E222:G222', 'E223:G223', 'E230:G230', 'E236:G236']

但是最后我得到了一个错误

  File "/home/y700/Env/spend/lib/python3.7/site-packages/openpyxl/worksheet/worksheet.py", line 611, in unmerge_cells
    del self._cells[(row, col)]
KeyError: (1083, 6)

如何解决?

1 个答案:

答案 0 :(得分:0)

使用命令KeyError: (8, 2)时遇到类似的KeyError sheet.unmerge_cells('B7:B19')。原因似乎是键(8,2)不在命令sheet._cell的输出字典中的键之一中。

我使用sheet.unmerge_cells('B7:B19')而不是使用sheet.merged_cells.remove('B7:B19'),它对我有用。