簡體   English   中英

如何使用 python openpyxl 從 excel 中按列名刪除列

[英]how to delete columns by column name from an excel using python openpyxl

我有一個 Excel 工作表,我想使用 python openpyxl 根據列名從中刪除某些列,因為列位置不固定。

每次我收到新報告時,它們的索引都會發生變化,但要刪除的列名稱每次都保持不變。 在下面的示例中,我想刪除名稱等於 = ["To be determined","No Value","Total"] 的列在此處輸入圖像描述

我已經嘗試獲取列索引號,以便我可以刪除那些使用索引值的列,但它沒有按預期工作。 在此處輸入圖像描述 其中 max_file 是 excel 文件路徑,sh2 是包含數據的 sheet2

您是否嘗試過使用

sh2.delete_cols(2,4)

2 是起始列,4 是列數。

找到了一個解決方案來檢索所需列名的列號: 在此處輸入圖像描述

Function 按列名刪除多列

# 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM