0

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 !!!!!!!!

3
  • 2
    Firstly, could you please use code formatting and an English dictionary to convert your question from unreadable garbage to something others can understand? Second, do you mean an Excel file or an XML file - the two aren't the same. Commented Jun 26, 2014 at 9:57
  • if item in cell.value is as clear as it gets: if the cell's value contains 2 (the value of the oddly named variable item), then print it. If you want to check for equality, use ==. Commented Jun 26, 2014 at 10:20
  • @user3488 The edits I made was to make the question clearer, if you disagree, please tell me why, and how your edits improved your question. Also, if you paste what it is after VAL it will help you to understand your problem of your code Commented Jun 26, 2014 at 10:30

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

If it helped please mark it as useful with the stick, so other people know how to solve the problem (and to close the question).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.