How To Insert and Delete Rows/Columns Using OpenPyXL?

Method

To insert rows or columns, use the `insert_rows` and `insert_cols` methods.

ws.insert_rows(idx,amount=1)

>>> ws.insert_rows(idx=2,amount=5)

ws.insert_cols(idx,amount=1)

>>> ws.insert_cols(idx=2,amount=2)

 

To delete rows or columns, use `delete_rows` and `delete_cols` methods.

ws.delete_cols(idx,amount=1)

ws.delete_rows(idx,amount=1)

Sample Code

#Inserting and Deleting Rows and Columns

#Import load_workbook function
from openpyxl import Workbook

#Create a new workbook
wb=Workbook()
#Get the active worksheet
ws=wb.active

#Insert 1 empty row above the 5th row
ws.insert_rows(5)
#Insert 3 empty rows above the 5th row
ws.insert_rows(5,3)

#Insert 1 empty column to the left of the 4th column
ws.insert_cols(4)
#Insert 3 empty columns to the left of the 4th column
ws.insert_cols(4,3)

#Delete the 5th row
ws.delete_rows(5)
#Delete the 4th column
ws.delete_cols(4)

#Delete 3 rows starting from the 5th row
#(including the 5th row)
ws.delete_rows(5,3)
#Delete 3 columns starting from the 4th column
#(including the 4th column)
ws.delete_cols(4,3)

wb.save('test.xlsx')
wb.close()

Leave a Reply

Your email address will not be published. Required fields are marked *