4

I want to read the .xls file data row by row using the value of any particular cell.

Consider there is a main column is ID, Name, Address, Age, Marks, Branch these are the main fields. Now i want to access the whole row whose (i==4). I want to access the row by using the value of particular cell.

Here i tried some

import xlrd
workbook = xlrd.open_workbook('sheet2.xls')
worksheet = workbook.sheet_by_name('Sheet1')
num_rows = worksheet.nrows - 1
num_cells = worksheet.ncols - 1
curr_row = -1
while curr_row < num_rows:
    curr_row += 1
    row = worksheet.row(curr_row)
    print 'Row:', curr_row
    curr_cell = -1
    while curr_cell < num_cells:
        curr_cell += 1
        # Cell Types: 0=Empty, 1=Text, 2=Number, 3=Date, 4=Boolean, 5=Error, 6=Blank
        cell_type = worksheet.cell_type(curr_row, curr_cell)
        cell_value = worksheet.cell_value(curr_row, curr_cell)
        print ' ', cell_type, ':', cell_value

So i am getting the output like

Row: 8
        2 : 96.0
        1 : Robert
        1 : Honore
        1 : 607-829-7943
        2 : 56.0
        1 : Faye
        1 : Wight
        1 : [email protected]

So its printing the entire row in this format. But i want to access the row by value. We can get the cell value using cell_value = worksheet.cell_value(1, 1) but how to get the row number for that cell value. And i want to get the entire row using the condition like(id==5) or (age==17) Please help me to sort out this.

1
  • take a look at the csv module for python. It has some support for Excel files, and can output rows either as a tuple or dict -- latter letting you do row['id'] docs.python.org/2/library/csv.html Commented May 31, 2014 at 18:18

1 Answer 1

2

What you're trying to do is called 'search' and you can't do this with xlrd. It doesn't offer search capabilities. You must iterate over the data in a loop and search it yourself.

It's pretty simple, but don't forget about performance. For example, if you plan to search something in sheet multiple times, than consider to cache parsed data after first lookup and save it to the memory for the next time.

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

Comments

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.