简体   繁体   中英

How to delete columns of excel with openpyxl without changing the merged cells?

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:

在此处输入图像描述 What is the correct approach?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM