FInding Value from excel sheet in python

↘锁芯ラ 提交于 2019-12-01 13:49:08
Haifeng Zhang

you can iterate the Excel sheet by range(sheet.nrows) and get row values based on the row number. The script below iterates the Excel sheet row by row and prints out the row that matches value 123456003. You can modify it to meet your requirement

$cat test.py

import xlrd

def open_file(path):
    wb = xlrd.open_workbook(path)
    sheet = wb.sheet_by_index(0)


    for row_num in range(sheet.nrows):
        row_value = sheet.row_values(row_num)
        if row_value[1] == 123456003:
            print row_value

if __name__ == "__main__":
    path = "data.xlsx"
    open_file(path)

$python test.py

[u'NS71282379_67698209', 123456003.0]

You will have to iterate over the rows and find the one you're interested in changing. Something like this:

for r in xrange(sheet.nrows):
  row = sheet.row(r)
  if row[0].value == "NS71282379_67698209":
    row[1].value = "new value"
    break

If you need to do this repeatedly, you could instead build a map from the first column values to the second column cells:

cells = dict((row[0].value, row[1])
             for row in (sheet.row(r) for r in xrange(sheet.nrows)))
cells["NS71282379_67698209"].value = "new value"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!