简体   繁体   English

逐行读取.xls文件数据

[英]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. 我想使用任何特定单元格的值逐行读取.xls文件数据。

Consider there is a main column is ID, Name, Address, Age, Marks, Branch these are the main fields. 考虑有一个主要的列是ID,Name,Address,Age,Marks,Branch这些是主要的字段。 Now i want to access the whole row whose (i==4). 现在我想访问其整数行(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. 我们可以使用cell_value = worksheet.cell_value(1,1)来获取单元格值,但是如何获取该单元格值的行号。 And i want to get the entire row using the condition like(id==5) or (age==17) Please help me to sort out this. 我希望使用像(id == 5)或(age == 17)这样的条件来获取整行。请帮我解决这个问题。

What you're trying to do is called 'search' and you can't do this with xlrd . 您尝试做的事情称为“搜索”,您无法使用xlrd执行此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. 例如,如果您计划多次在工作表中搜索某些内容,而不是考虑在首次查找后缓存已分析的数据,并将其保存到内存中以供下次使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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