Reputation: 325
I have an xlsx file, which contains a specific number of sheets.
I want a python script to search the specified sheet for a value in the cell, and if found delete the entire row.
The script i have is currently built to search a row corresponding to a value and change the value. I have tried modifying the script without any success.
This is my code:
import openpyxl
for f in files:
if f[-4:] == "xlsx":
book = openpyxl.load_workbook(f)
sheet = book.active
for idx, row in enumerate(sheet.iter_rows()):
if row[0].value == "some_value":
row[1].value = 1
book.save(f)
Any help is appreciated.
Running on Python3, on PyCharm, on Windows 10.
Upvotes: 0
Views: 253
Reputation: 2086
Here is the solution to delete the row depending on the value condition:
import openpyxl
f = "testFile.xlsx"
if f[-4:] == "xlsx":
book = openpyxl.load_workbook(f)
sheet = book.active
[sheet.delete_rows(idx + 1) for idx, row in enumerate(sheet.values) if row[0] == "some value"]
book.save(f)
OR
import openpyxl
f = "testFile.xlsx"
if f[-4:] == "xlsx":
book = openpyxl.load_workbook(f)
sheet = book.active
for idx,row in enumerate(sheet.values):
if row[0] == "some value":
sheet.delete_rows(idx+1)
book.save(f)
Upvotes: 1