2016-11-15 41 views
0

我想從使用xlrd的Excel電子表格的第25列中獲取最大值。這就是我所做的。使用XLRD從excel列中獲取最大值

import xlrd 
book = xlrd.open_workbook("File Location\Filename.xlsx") 
sheet = book.sheet_by_index(0) 

def follow_up(): 
    col = 24 
    row = 1 
    max = 1 
    while row < 100: 
     a = sheet.cell(row, col).value 
     if a>max: 
      return a 
     else: 
      return max 
     row+=1 

print(follow_up()) 

我跑進小區的問題,在一列小於100倍的值(給我IndexError)和代碼不會在一列超過100個值細胞起作用。如果我知道如何獲得列中值的數量,這可以被修復。但我想知道是否有人知道「更乾淨」的方式來做到這一點。

非常感謝。

回答

2

嘗試:

import xlrd 
book = xlrd.open_workbook("File Location\Filename.xlsx") 
sheet = book.sheet_by_index(0) 

def follow_up(): 
    col = 24 
    return max(sheet.col_values(col)) 

print(follow_up()) 

我希望這有助於。

1

試試這個:

import xlrd 
book = xlrd.open_workbook("File Location\Filename.xlsx") 
sheet = book.sheet_by_index(0) 

def follow_up(): 
    col = 24 
    return max(sheet.col_values(col, start_rowx=1, end_rowx=101)) 
    #with start_rowx and end_rowx you can define the range 
    #we start with 1 so as to skip the header row 

print(follow_up()) 

col_values()返回你所提到的列中的所有值的列表。

希望這會有所幫助:)