2010-09-23 71 views
2

我使用Python xlrd http://scienceoss.com/read-excel-files-from-python/从一个Excel工作表Python的xlrd数据提取

我的问题是,如果我读在Excel工作表第一单元为“员工姓名”一列中读取数据

还有名为另一行,其第一单元“员工姓名”

我们如何阅读的最后一列从最后一排,其在第一cell.Ignoring以前

wb = xlrd.open_workbook(file,encoding_override="cp1252") 
    wb.sheet_names() 
    sh = wb.sheet_by_index(0) 
    num_of_rows = sh.nrows 
    num_of_cols = sh.ncols 
    valid_xl_format = 0 
    invalid_xl_format = 0 

    if(num_of_rows != 0): 
    for i in range(num_of_rows): 
     questions_dict = {} 
     for j in range(num_of_cols): 
       xl_data=sh.cell(i,j).value 
       if ((xl_data == "Employee name")): 
        # Regardless of how many "Employee name" found in rows first cell,Read only the last "Employee name" 
有“员工姓名” 10

回答

5

我使用Python xlrd http://scienceoss.com/read-excel-files-from-python/从一个Excel工作表

你需要想想你读数据正在做的,而不是抓住一些博客代码,并离开像wb.sheet_names()完全不相关的东西,并省略与您的要求非常相关的部分,如first_column = sh.col_values(0)

这里是如何找到最后的“无所谓”在列A(第一列)的ROW_INDEX - 未经测试:

import xlrd 
wb = xlrd.open_workbook(file_name) 
# Why do you think that you need to use encoding_overide? 
sheet0 = wb.sheet_by_index(0) 
tag = u"Employee name" # or u"Emp name" or ... 
column_0_values = sheet0.col_values(colx=0) 
try: 
    max_tag_row_index = column_0_values.rindex(tag) 
    print "last tag %r found at row_index %d" % (
     tag, max_tag_row_index) 
except IndexError: 
    print "tag %r not found" % tag 

现在,我们需要解释“我们如何阅读的最后一列起点与最后行,其在第一小区

假设‘最后一列’指的是一个具有与Column_Index == sheet0.ncols有“雇员姓名” - 1,则:

last_colx = sheet0.ncols - 1 
required_values = sheet0.col_values(colx=last_colx, start_rowx=max_tag_row_index) 
required_cells = sheet0.col_slice(colx=last_colx, start_rowx=max_tag_row_index) 
# choose one of the above 2 lines, depending on what you need to do 

如果这不是你的意思(这很可能,因为它忽略了一大堆数据(为什么你只想读最后一列?),请尝试用例子来解释你的意思。

可能要遍历剩余的细胞:

for rowx in xrange(max_tag_row_index, sheet0.nrows): # or max_tag_row_index + 1 
    for colx in xrange(0, sheet0.ncols): 
     do_something_with_cell_object(sheet0.cell(rowx, colx)) 
+0

给出的代码只是一个例子。无论如何谢谢你的解决方案... – Hulk 2010-09-23 17:54:21

0

很难理解你在问什么。
发布样本数据可能有助于使您的意图更清晰。

您是否尝试过遍历反向数据集?,例如:

for i in reversed(range(num_of_rows)): 
    ... 
    if xl_data == "Employee name": 
     # do something 
     # then break since you've found the final "Employee Name" 
     break 
+0

免得说第一行第一个单元是“的Emp名”,第二行第一个单元是“的Emp名”排和第三排第一单元“的Emp名“在这种情况下,我想读第三个单元 – Hulk 2010-09-23 06:28:40