Search code examples
pythonexcelxlrdxlwt

How to iterate over a Row or Column of an Excel sheet using Python and look for specific value in cells?


Below is a code I literally copied from someone. It reads and updates an existing Excel file. What I want is to add another functionality of iterating over each row or column and look for a specific value. Then I want to update that specific cell with a new value.

import xlwt
import xlrd
from xlutils.copy import copy

rb = xlrd.open_workbook("imtiaz.xls")
wb = copy(rb)
w_sheet = wb.get_sheet(0)
w_sheet.write(0,1,45)


w_sheet.write(1,1,46)
wb.save("imtiaz.xls")

Solution

  • To iterate over an excel sheet, you can use the sheet.nrows() function in the xlrd module.

    import xlrd
    
    workbook = xlrd.open_workbook("my_path") # Opens your file
    sheet = workbook.sheet_by_index(0) # Gets the first sheet
    
    for row in range(sheet.nrows): # Iterates over your sheet
        row_value = sheet.row_values(row)
        if row_value[1] == "my_value":
            print row_value