简体   繁体   中英

openpyxl: adding values to cells using a for loop

I am trying to increase the value inside of each cell by 1.

import openpyxl as xl
from openpyxl import Workbook

wb = Workbook()
sheet = wb['Sheet']
age = sheet.cell(row=1, column=1, value='age')
gender = sheet.cell(row=1, column=2, value='gender')
genre = sheet.cell(row=1, column=3, value='genre')

val = 20

for row in range(2, 11):
    cell = sheet.cell(row=row, column=1)
    cell.value(val)

wb.save('music.xlsx')

I keep getting an error:

line 14, in <module>
    cell.value(val)
TypeError: 'NoneType' object is not callable

I know that there is a lot of errors in my code, however I do not know how to fix it.

In the cell object, value is not a method, it's property.

So use below code:

import openpyxl as xl
from openpyxl import Workbook

wb = Workbook()
sheet = wb['Sheet']
age = sheet.cell(row=1, column=1, value='age')
gender = sheet.cell(row=1, column=2, value='gender')
genre = sheet.cell(row=1, column=3, value='genre')

val = 20

for row in range(2, 11):
    cell = sheet.cell(row=row, column=1)
    cell.value = val

wb.save('music.xlsx')

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