简体   繁体   中英

Search into excel file with python

First of all, I'm a python beginner so I apologize for the trivial question :DI try to search into a *.xls file a specific word using python (v 2.7)

Short problem description/specification : 1. test.xls is the input file 2. The target word is 2, I want exctract only the cell which contains only 2 and not sometihngs with 2 (eg cell value = 2 -> right! cell value=2345-> wrong !!)

below the code :

book = open_workbook('test.xls',on_demand=True)  
item = 2  
row=-1  
n=0  
for name in book.sheet_names():  
    if name.endswith('Traceability Matrix'):  
        sheet = book.sheet_by_name(name)  
        rowIndex = -1  
        for cell in sheet.col(1): #  
            n=n+1  
            if  item  in cell.value:  
                print "VAL ",cell.value  
                print "ROW ",sheet.row(n)  
                break  
    if row != -1:  
        cells = sheet.row(row)  
        for cell in cells:  
            print">>", cell.value  

book.unload_sheet(name)  

Now, my output is list of rows which contains NOT only 2 (see wrong case above, point 2), see below the "print" results:

ROW [text:u'SRS5617\\nSRS5618\\nSRS5619\\nSRS5620', text:u'RQ - 5282', empty:'', text:u'Function Plus', text:u'See Note ', empty:'', empty:'', empty:'', empty:'', empty:'', empty:'', text:u'Code inspection', text:u'(**), 2']

Someone can help me? Some suggestion?

Thanksssss !!!!!!!!

Your problem is on this lines

        if  item  in cell.value:
            print "VAL ",cell.value
            print "ROW ",sheet.row(n)
            break

That search if a "2" is on the cell.value, not if it is 2.

it could be changed to if int(cell.value) == int(item):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM