0

I have made the following code on python 3.7 to delete column from excel

import openpyxl
from openpyxl import load_workbook

path=r'path\SAMPLE_TASK.xlsx'
wb=openpyxl.load_workbook(path)
ws=wb.active

a=int(input("Enter Column: "))
ws.delete_cols(a)
wb.save(path)

I am able to enter integer in a as input and delete a column But how do I use the column name to delete for example is instead of column 1 I need to enter 'A' column or is my column has a title 'Address; then if i enter "address' as user input it should delete that column Also how can i delete multiple columns

Gavya Mehta
  • 211
  • 6
  • 20
  • 1
    You can do the same through `pandas`. Refer [here](https://stackoverflow.com/questions/28538536/deleting-multiple-columns-based-on-column-names-in-pandas) – Gokul nath Mar 24 '20 at 07:02
  • ReadTheFineTutorial [openpyxl tutorial](https://openpyxl.readthedocs.io/en/stable/editing_worksheets.html?highlight=delete_cols#deleting-rows-and-columns), [column_index_from_string](https://openpyxl.readthedocs.io/en/stable/api/openpyxl.utils.cell.html#module-openpyxl.utils.cell) – stovfl Mar 24 '20 at 09:09

1 Answers1

0

Try to use this code. But first, let user to enter columns in cols_list.

# creating an empty list
cols_list= []

# number of elements as input - how many columns to delete
n = int(input("Enter number of elements : "))

# iterating till the range
for i in range(0, n):
    elem = int(input()) # here you can add your columns, this way: 'A'

    cols_list.append(elem) # adding the element

#function
    wb = openpyxl.load_workbook(path)
    ws = wb.active
    sheet = wb["Sheet1"] 
    
    for i in cols_list:
    
        which_cols= openpyxl.utils.cell.column_index_from_string(i)
        ws.delete_cols(which_cols, 1)
JST
  • 1
  • 1