我在删除列时遇到了类似的问题,与此类列相交的合并单元格最终没有改变。
这以更令人满意的方式工作。
代码提供了delete_row()函数,可以用来模仿Excel的行为,并相应地移动合并的单元格:
import openpyxl
from openpyxl.utils import range_boundaries
from openpyxl.utils.cell import _get_column_letter
from openpyxl.worksheet.cell_range import CellRange
def delete_row(target_row):
# Assuming that the workbook from the example is the first worksheet in a file called "in.xlsx"
workbook = openpyxl.load_workbook('in.xlsx')
ws = workbook.worksheets[0]
affected_cells = [] # array for storing merged cells that need to be moved
row = target_row # specify the row that we want to delete
sheet_boundary = [4,6] # specify how far to search for merged cells in the sheet in the format of [ max_col, max_row ]
## Define a range of cells that are below the deleted row
# top left corner of the range; will be A2
tl_corner = "A"+str(row)
# bottom right corner of the row; will be D6
br_corner = _get_column_letter(sheet_boundary[0]) + str(sheet_boundary[1])
target_row_range_string = tl_corner+":"+br_corner
# express all cells in the row that is to be deleted as object CellRange from openpyxl
target_range = CellRange(range_string=target_row_range_string)
# loop over all merged cells in the sheet
for merged_cell_range in ws.merged_cells.ranges:
# if merged_cell is within target_range add current merged cell to 'affected_cells'
if merged_cell_range.issubset(target_range):
print("Cell '"+str(merged_cell_range)+"' is within range of '"+str(target_range)+"'")
affected_cells.append(merged_cell_range)
# unmerge all affected cells
for cell in affected_cells:
# get a tuple of coordinates, instead of Xlsx notation
cell_range = range_boundaries(cell.coord)
print("'"+str(cell)+"' ---> '"+str(cell_range)+"'")
# unmerge the affected cell
ws.unmerge_cells(start_column = cell_range[0], start_row = cell_range[1],
end_column = cell_range[2], end_row = cell_range[3])
# perform row deletion as usual
ws.delete_rows(row)
# merged all affected cells
for cell in affected_cells:
# get a tuple of coordinates, instead of Xlsx notation
cell_range = range_boundaries(cell.coord)
# merge back the affected cell, while lifting it up by one row
ws.merge_cells(start_column = cell_range[0], start_row = cell_range[1]-1,
end_column = cell_range[2], end_row = cell_range[3]-1)
# save the edited workbook
workbook.save('out.xlsx')
# call our custom function, specifying the row you want to delete
delete_row(2)
这会找到与target_range 相交的所有合并单元格,该范围以删除的行开始并以sheet_boundary 定义的范围结束,并首先将它们取消合并。
只有完全在target_range 内的合并单元格才会被更改。
如果合并单元格的一部分在target_range 内,则不会对该单元格执行任何操作。
然后它删除所需的行,并合并所有受影响的单元格,同时考虑到它们已向上移动一行。