Home » excel » python – Open specific excel file/sheet to get a specific content cell location

python – Open specific excel file/sheet to get a specific content cell location

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a list of excel files and their corresponding sheet number. I need python to go to those sheets and find out the cell location for a particular content. Can someone point out the error in my code? Thanks in advance

import xlrd
value = 'Avg.'
filename = ('C:/002 Av SW W of 065 St SW 2011-Jul-05.xls', 'C:/003 Avenue SW West of 058 Street SW 2012-Jun-23.xls')
sheetnumber = ('505840', '505608')
dictionary = dict(zip(filename, sheetnumber))
for item in dictionary:
    book = xlrd.open_workbook(item)
    sheet = book.sheet_by_name(dictionary[key])
    for row in range(sheet.nrows):
        for column in range(sheet.ncols):
            if sheet.cell(row,column).value == value:
                print row, column
How to&Answers:

You don’t need to make a dictionary. Iterate over zip(filename, sheetnumber):

for name, sheet_name in zip(filename, sheetnumber):
    book = xlrd.open_workbook(name)
    sheet = book.sheet_by_name(sheet_name)
    for row in range(sheet.nrows):
        for column in range(sheet.ncols):
            if sheet.cell(row,column).value == value:
                print row, column