Problems using operators and openpyxl

I recently started learning python coding language and I seem to have run into some problems in my journey trying to use + operator to append new int() value to already existing int() value.

My question is simply:

How to use + operator in python to already existing value in excel? Afterwards, I try to call the new value from the specific cell in excel.

Do I need to append a value to a whole column or can I just change the value in the specific cell in Excel using the + operator on existing cell-value?

def add():
    from openpyxl import Workbook
    workbook = Workbook()
    sheet = workbook.active

    sheet["A1"] = 'Marginal Social Benefit'
    sheet["B1"] = 'Marginal Social Cost'

    x = sheet["A2"]
    y = sheet["B2"]

    vad = int(input())
    vid = int(input())

    sheet["A2"] = (x + vad)
    sheet["B2"] = (y + vid)
    workbook.save(filename='hey.csv')

add()

Upvotes: 0

Views: 102

Answers (1)

SodaCris
SodaCris

Reputation: 535

for accessing existing cells, you can use .value.

init:

from openpyxl import Workbook,load_workbook
workbook = Workbook()
sheet = workbook.active
sheet["A1"] = 'Marginal Social Benefit'
sheet["B1"] = 'Marginal Social Cost'
sheet["A2"] = 11
sheet["B2"] = 22
workbook.save(filename='hey.xlsx')

then:

workbook = load_workbook('hey.xlsx')
sheet = workbook.active
x = sheet["A2"]
y = sheet["B2"]
vad = int(input())
vid = int(input())
sheet["A2"] = (x.value + vad)
sheet["B2"] = (y.value + vid)
workbook.save(filename='hey.xlsx')

Upvotes: 1

Related Questions