Search code examples
pythonloopsopenpyxl

Skipping over the first worksheet in a loop in Openpyxl


I'm looking to skip the first worksheet before searching for a specific number in the remaining sheets. My code so far:

wb = load_workbook("example.xlsx")


sheet1 = wb["Sheet1"]

sheet2 = wb["Sheet2"]

sheet3 = wb["Sheet3"]

for sheet in wb.worksheets:
    #print(sheet)
    for row in sheet.iter_rows(2,sheet.max_row-1):
        numbers = row[9].value
        if numbers in [652850]:
            sheet3.append((cell.value for cell in row))

Solution

  • You just want to continue on the first sheet. You could do that by checking the sheet title but can simply check if it is the first of the list in wb.worksheets.
    see below;

    for sheet in wb.worksheets:
        #print(sheet)
        if sheet == wb.worksheets[0]:
            continue
        for row in sheet.iter_rows(2,sheet.max_row-1):
            numbers = row[9].value
            if numbers in [652850]:
                sheet3.append((cell.value for cell in row))