Search code examples
openpyxlpython-3.7

How to access the values of a tuple in a loop?


I'm trying to make a calculator that will read values from an excel worksheet and calculate the answer given an operator. I can't figure out a way to write it as such that it will access the values stored within the tuple it's reading the cell values in as

Code:

def excel_math(filename):

from openpyxl import load_workbook
wb = load_workbook(filename)
ws = wb.active
for row in ws.rows:
    operator = row[0].value
    nums = row[1:]
    if operator == '+':
        subtotal = int(nums[0])
        for numcell in nums[1:]:
            subtotal += int(nums)
        print(subtotal)

Solution

  • openpyxl and Python provide several convenient functions for this kind of task. First of all you should only put the relevant code into the function, so you probably want a separate function for passing in the worksheet.

    def row_summer(ws):
        for row in ws.iter_rows(values_only=True):
            op, *values = row
            if op == "+":
                 return sum(values)