FInding Value from excel sheet in python

和自甴很熟 提交于 2019-12-01 10:26:33

问题


I have an excel sheet (data.xlxs) with the following pattern of data with more than 200 rows.

NS71282379_67698209    123456001
NS71282379_56698765    123456002
NS71282379_67698209    123456003
.
.
.

Now in my script, I am trying to find the corresponding value for 123456003 as NS71282379_67698209. In my script, I want to replace 123456003 with its value from the excel sheet. I used xlrd to import the sheet but haven't found any method which easily allows me to find the corresponding value. How can I do this smartly?


回答1:


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]



回答2:


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"


来源:https://stackoverflow.com/questions/36754941/finding-value-from-excel-sheet-in-python

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