Search code examples
pythonexcelxlrd

Is there a way to search for a value in an Excel spreadsheet and print out what row the value is in using Python?


I am trying to use Python to look for a value in an Excel spreadsheet, and have Python print out the row that value is in.

For example, I know that the number 10 is in a certain column in my spreadsheet, but there are too many rows to search through manually, so I would like to use Python to find out which row it is in.


Solution

  • So for example, if you're looking for "10" in a spreadsheet of various numbers a easy way to solve this is to use the xlrd library and loop through each cell and check if it contains "10"

    for row in range(sheet.nrows):
       for col in range(sheet.ncols):
          if sheet.cell_value(row, col) == 10:
             print row, col
    

    Keep in mind that this is not the most effective way of doing this. If you have a significant amount of data you could use pandas, import one csv as a "Objective_Table" dataframe and import another as a "Search_Table" and then use the merge feature.

    Hope this helps.