2010-09-23 95 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