简体   繁体   中英

Read .xls file data row by row python

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 : Faye.A.Wight@mailinator.com

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.

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.

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