Find if a value exists in a column in Excel using python

CascadeHiker picture CascadeHiker · Jun 6, 2015 · Viewed 13.5k times · Source

I have an Excel file with one worksheet that has sediment collection data. I am running a long Python script.

In the worksheet is a column titled “CollectionYear.” Say I want the year 2010. If the year 2010 exists in the “CollectionYear” column, I want the rest of the script to run, if not then I want the script to stop.

This seems like an easy enough task but for the life of me I cannot figure it out nor find any examples.

Any help would be greatly appreciated.

Answer

Joel Johnson picture Joel Johnson · Jun 6, 2015

I use xlrd all the time and it works great for me. Something like this might be helpful

from xlrd import open_workbook

def main():
    book = open_workbook('example.xlsx')
    sheet = book.sheet_by_index(0)
    collection_year_col = 2 #Just an example
    test_year = 2010
    for row in range(sheet.nrows):
        if sheet.cell(row,collection_year_col).value == test_year:
            runCode()

def runCode():
    #your code

I hope this points you in the right direction. More help could be given if the details of your problem were known.