Reputation: 109
I need to delete some rows in an excel file based on if the cells are empty. There are 2 cells that can contain some user data and if either one of those cells has the data, I need to keep it, otherwise, if both cells are empty, delete the row.
I figured out how to delete rows based on if 1 cell is empty. I want it to look at column 6 and column 8, if both are empty, delete the row. If only one of them is empty, keep the row.
current code is this
from openpyxl import load_workbook
wb = load_workbook('Pull-1.xlsx')
sheetlist = wb.get_sheet_names()
sheet = wb.get_sheet_by_name(sheetlist[0])
rownumber = 1
for row in sheet.iter_rows(min_row=2, max_row= sheet.max_row, min_col=8, max_col=8, values_only=True):
rownumber += 1
for i in range(sheet.max_row, 1, -1):
if sheet.cell(row=i, column=8).value is None:
sheet.delete_rows(i, 1)
wb.save('pull-1mod.xlsx')
Also... If I have something extra that is not needed, please let me know. I'm just learning, and pieced this together from researching on here.
Upvotes: 1
Views: 932
Reputation: 2129
Change if-statement to:
if sheet.cell(row=i, column=8).value is None and sheet.cell(row=i, column=6).value is None:
Upvotes: 2