How to delete rows of a sheet using Openpyxl in Python
In this tutorial, we are going to see how to delete the rows of an excel sheet in Python. This can be done by using the openpyxl library. This library is used to work with excel sheets in Python.
First, import the openpyxl library.
The sample excel file we are going to use in the code is:
Now access the excel workbook using the
load_workbook(path) function from the openpyxl library. Pass the excel file path to the function.
path = 'abc.xlsx'#excel file path wb = openpyxl.load_workbook(path)
Now select the excel sheet from the loaded workbook.
sheet = wb.active #specify the sheet name to select other than the active sheet
delete_rows( ): function to delete rows
delete_rows(idx) is a function from the openpyxl library which is used to delete rows from an excel sheet. idx is the function parameter that we need to pass. It specifies the row number (index) that is to be deleted.
Now using this function delete the 3 rd row from an excel sheet.
print("Maximum rows before removing : ",sheet.max_row) sheet.delete_rows(idx=3) path1 = 'final.xlsx' wb.save(path1) print("Maximum rows after removing : ",sheet.max_row)
Print the maximum number of rows before and after the deletion for reference.
max_row method returns the maximum number of rows from the sheet.
specify the new file name/path (path1) to create the new excel file. After deletion, save the modified excel file in a final file using the
save(path) method. It saves the workbook at the specified path.
Maximum rows before removing : 6 Maximum rows after removing : 5
The ‘final.xlsx’ file will be created in your current folder from which the 3 rd row will be deleted.