Search code examples
pythonexcelif-statementrowopenpyxl

deleting rows if matching partial string in openpyxl


I am trying to delete every row containing a partial string. It is correctly identifying the correct rows containing the partial string, it is just not deleting them from the sheet.

Here is my attempt:

for row in sheet10.iter_rows(2,sheet.max_row-1):
    message = row[10].value
    if  message != None and 'My partial string' in message:
        print(row[10].value)
        print(row[0].row)
        sheet10.delete_rows(row[0].row, 1)
        ```

Solution

  • You should make a full MRE but anyways, here is an example for the general logic :

    wb = load_workbook("file.xlsx")
    
    ws = wb.active
    
    rows_to_delete = [
        row[0].row for row in ws.iter_rows()
        if any("foo" in str(cell.value) for cell in row)
    ] # [2, 3, 5]
    
    for row_idx in reversed(rows_to_delete): #to avoid the index from shifting-up
        ws.delete_rows(row_idx)
    
    wb.save("new_file.xlsx")
    

    Or, as suggested by @Charlie Clark, for more readability, you can construct the indexes this way :

    rows_to_delete = [
        idx for idx, row in enumerate(
            ws.iter_rows(values_only=True), start=1) #or ws.values
        if any(isinstance(cell, str) and "foo" in cell for cell in row)
    ]  # [2, 3, 5]
    

    Another variant :

    rows_to_delete = []
    
    for idx, row in enumerate(ws.values, start=1):
        check = any(isinstance(value, str) and "foo" in value for value in row)
        if check:
            rows_to_delete.append(idx)
    

    Output :

    enter image description here