I tried to delete the first columns of the excel file in https://drive.google.com/open?id=1G6nE5wiNRf5sip22dQ8dfhuKgxzm4f8E
.
Here is my code:
dg = openpyxl.load_workbook('sample.xlsx')
sheet_obj = dg.active
sheet_obj.delete_cols(1)
dg.save('sample2.xlsx')
However, the position of the column names changes.
Before:
After:
You will have to modify the merged cell ranges accordingly.
def delete_col_with_merged_ranges(sheet, idx):
sheet.delete_cols(idx)
for mcr in sheet.merged_cells:
if idx < mcr.min_col:
mcr.shift(col_shift=-1)
elif idx <= mcr.max_col:
mcr.shrink(right=1)
delete_col_with_merged_ranges(sheet_obj, 1)
Here is an analogous function for deleting a row within a merged cell ( credit ):
def delete_row_with_merged_ranges(sheet, idx):
sheet.delete_rows(idx)
for mcr in sheet.merged_cells:
if idx < mcr.min_row:
mcr.shift(row_shift=-1)
elif idx <= mcr.max_row:
mcr.shrink(bottom=1)
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.