![](/img/trans.png)
[英]How to search specific column name ( not A ,B etc) such as Name ,Marks in excel using python and openpyxl?
[英]how to delete columns by column name from an excel using python openpyxl
您是否嘗試過使用
sh2.delete_cols(2,4)
2 是起始列,4 是列數。
# 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.