简体   繁体   中英

Get the maximum value from an excel column using XLRD

I would like to get the maximum value from 25th column of an excel spreadsheet using xlrd. Here's what I did.

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())

I run into an issue for cells with less than 100 values in a column (gives me IndexError) and the code won't work for cells with more than 100 values in a column. This can be fixed if I know how to get the number of values in a column. But I was wondering if anyone knows a "cleaner" way to do this.

Try:

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())

I hope this helps.

Try this:

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() returns a list of all values in the column you mention.

Hope this helps :)

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