如何使用python openpyxl按列名称从excel中删除列

db2dz4w8  于 2022-11-19  发布在  Python
关注(0)|答案(2)|浏览(235)

我有一个Excel工作表,我想从其中删除某些列的列名使用python openpyxl作为列的位置是不固定的。
它们的索引可以在我每次获得新报告时更改,但要删除的列名每次都保持不变。在下面的示例中,如果列名等于= [“To be determined”,“No Value”,“Total”]

,我希望删除这些列
我已经尝试获取列索引号,以便删除使用索引值的列,但无法按预期工作。

,其中max_file是excel文件路径,sh2是包含数据的sheet2

htrmnn0y

htrmnn0y1#

你试过用

sh2.delete_cols(2,4)

2是起始列,4是列数。

lbsnaicq

lbsnaicq2#

按列名删除多个列的函数

# Even if your cell names are not like 'B12' instead only 'B'. That also can be done just let me know in the comment
list_of_cell_names_need_to_be_deleted = ['B1', 'C2', 'E7', 'A5']

def delete_columns_by_name(list_of_cell_names_need_to_be_deleted):

    for i in list_of_cell_names_need_to_be_deleted:

        # For the first iteration first it splits 'B1' to ('B',1) and stores 'B' to the assigned variable below
        cell_name_only_alpha = openpyxl.utils.cell.coordinate_from_string(i)[0]

        # After splitting it, we will store the index of the letter exctrated ( here for first iteration it will be 'B' and hence index will be 2 )
        index_value = openpyxl.utils.cell.column_index_from_string(cell_name_only_alpha)
        
        # Now let's delete the colu
        # If you don't know what is ws, here is a brief information
        # wb - Used to mention the name of the file.
        # ws - Used to mention the sheet name of the file. (There may be more than one sheet within an excel file)
        # For more info : https://openpyxl.readthedocs.io/en/stable/tutorial.html
        ws.delete_cols(index_value,1)


delete_columns_by_name(list_of_cell_names_need_to_be_deleted)

# NOTE : At the end don't forget to save the file
# Code to save the file : wb.save(name_of_file_here)

wb.save(name_of_file_here)

相关问题