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

孤者浪人 提交于 2019-11-28 06:10:38

问题


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.


回答1:


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.




回答2:


Try using xlwings library to interface with Excel from python

example from their docs:

from xlwings import Workbook, Sheet, Range, Chart
wb = Workbook()  # Creates a connection with a new workbook
Range('A1').value = 'Foo 1'
Range('A1').value
>>> 'Foo 1'
Range('A1').value = [['Foo 1', 'Foo 2', 'Foo 3'], [10.0, 20.0, 30.0]]


来源:https://stackoverflow.com/questions/30678721/find-if-a-value-exists-in-a-column-in-excel-using-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!