applestooragnes
applestooragnes

Reputation: 119

How do I use OpenPyXL for a specified range?

How do I divide each value in one column by each value in a separate column?

Do I use the range function?

Example:

for i in range(2,80):
    sheet['D{}'.format(i)] = '=C1/E1, C2/E2, C3/E3, etc...'

Upvotes: 0

Views: 472

Answers (1)

Abdou
Abdou

Reputation: 13274

You can get it done by applying division operations to the actual values of the cells. Your code is pretty close; you just need to correct the right hand side by accessing the cell values:

import openpyxl


wb = openpyxl.load_workbook('path/to/xl/file', read_only = False)

# Assuming you are working with Sheet1
sheet = wb['Sheet1']

for i in range(2,80):
    try:
        sheet['D{}'.format(i)].value = int(sheet['C{}'.format(i)].value)/int(sheet['E{}'.format(i)].value)
    except ValueError:
        print("{} and/or {} could not be converted to int.".format(sheet['C{}'.format(i)].value, sheet['E{}'.format(i)].value))

wb.save('path/to/new/xl/file')

I hope this helps.

Upvotes: 1

Related Questions