H2O
H2O

Reputation: 173

Search into excel file with python

First of all, I'm a python beginner so I apologize for the trivial question :D I 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 (e.g. 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 !!!!!!!!

Upvotes: 0

Views: 10696

Answers (1)

llrs
llrs

Reputation: 3397

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):

Upvotes: 2

Related Questions