Skip to content
Advertisement

How to delete rows in Excel if cells in specific column are blank using python openpyxl?

I am a Python beginner (and also new to Stack Overflow) and I’ve recently discovered openpyxl which has been a lifesaver, but I cannot solve the following issue.

I have a spreadsheet with data in columns A-I. The spreadsheet is a course-completion report which tells me if customers have completed a particular course that my company offers. If the customer has completed the course, the date of completion is listed in column “I” as “mm/dd/yyyy” format. If the customer has NOT completed the course, the cell in column “I” is blank. I would like to delete all rows where the value in column “I” is blank. I have tried the following:

for cell in ws['I'][1:]:
    if cell.value is None:
        ws.delete_rows()

This didn’t throw any error messages, but it also did not work. I also tried:

for cell in ws['I'][1:]:
    if cell.value == None:
        ws.delete_rows()

Again, I am a beginner, so I may be missing something very simple. Any and all help is greatly appreciated! Thank you.

Advertisement

Answer

It seems that you just need to specify the row to be deleted:

for cell in ws['I'][1:]:
    print(cell.value)
    if cell.value == None:
        ws.delete_rows(cell.row)
    

also you have to save the changes:

wb.save('yourfile.xlsx')
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement