[英]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
.我试图删除https://drive.google.com/open?id=1G6nE5wiNRf5sip22dQ8dfhuKgxzm4f8E
中 excel 文件的第一列。
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.但是,列名的 position 发生了变化。
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 ):这是一个类似的 function 用于删除合并单元格中的一行( 信用):
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.