Search code examples
pythonif-statementopenpyxlstring-comparison

Openpyxl: backfill a row that has a cell with a partial string match?


I'm working on a program that filters a large .xlsx file and then splits those filtered sets out onto new sheets in a new workbook.

One problem I'm trying to fix, is recreating the old format on the new sheets using openpyxl. I can't seem to figure out how to make a partial string match not result in a TypeError.

Relevant code snippet:

def set_style(sheet, type_row, group1, group2):
    for row in sheet.iter_rows():
        for cell in row:
            if row[type_row].value in group1:
                if 'START:' in cell.value:
                    cell.fill = PatternFill(start_color='00FFOO', end_color='00FF00', fill_type='solid')
                    cell.font = Font(bold=True)
                if 'END:' in cell.value:
                    cell.fill = PatternFill(start_color='99FF99', end_color='99FF99', fill_type='solid')
                    cell.font = Font(bold=True)
            if row[type_row].value in group2:
                cell.font = Font(bold=True)
                cell.fill = PatternFill(start_color='FFA500', end_color='FFA500', fill_type='solid')

The if-statement related to group2 works fine on it's own, it's only when I try to check if "START:" or "END:" that ends up resulting in my error.

Any help would be appreciated!


Solution

  • I managed to find out what the problem was and sort of worked around it:

    if row[5].value is not None:
      if row[5].value != int:
         if 'START:' in row[5].value:
    #<rest of code here>