Insert a row in specific position into Excel using openpyxl in Python

This tutorial will see how to insert a row in a specific position into an Excel file using Openpyxl in Python. Openpyxl is a Python library using which we can perform operations on an excel file.

First of all import the required functions from the Openpyxl library.
load_workbook: It is a function used to load the excel file in the code.

from openpyxl import load_workbook

The excel file which we are going to use in the code is:

Insert a row in specific position into Excel using openpyxl

Now pass the file path to the load_workbook function and extract the excel file in code. And select the sheet from the excel file.
.active selects the active sheet from the excel workbook. You can specify the sheet name to select any other sheet.

path = 'IRIS.xlsx'#Excel file path
wb = load_workbook(path)
sheet = wb.active #extract the sheet

insert_rows( ): Function to insert rows

insert_rows(idx) is a function from the openpyxl library used to insert rows into an excel sheet. idx is the function parameter that specifies the position at which the row is to be inserted.
Now using this function insert the row in an excel sheet.

After inserting save the modified file using the save() function. This function is to save the workbook that takes the file path as an argument and saves the changes.

print("Maximum rows before inserting : ",sheet.max_row)
sheet.insert_rows(idx=7)
wb.save(path)
print("Maximum rows after inserting : ",sheet.max_row)

Print the row number from the excel sheet before insertion and after insertion for reference.

Output:

Maximum rows before inserting : 10
Maximum rows after inserting : 11

After the insertion of a row, the file looks like this:

sheet.insert_rows(idx=7)

Also, refer to How to delete rows of a sheet using Openpyxl in Python

Leave a Reply

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