简体   繁体   中英

Python openpyxl loop data in cells

I am trying to loop the value 2 into the cells in the given range but when the script runs and I check my excel sheet the cells are empty.

from openpyxl import Workbook

wb = Workbook()

ws = wb.active

n = 1
ws.title = 'Day '+str(n)

ws['A1'] = 42


import datetime

ws['A2'] = datetime.datetime.now()

c = ws['A4']
ws['A4'] = 4

d = ws.cell(row=4, column=2, value=10)

cell_range = ws['A5':'A7']

for cell in cell_range:
    cell.value = 2

wb.save("sample.xlsx")

what is the error here?

(Note: The question originally listed the problematic assignment as cell = 2 )

There are two problems.

First, in order to assign a value to a cell assign to the cell's value attribute:

cell.value = 2

Second, for cell in cell_range actually returns tuples containing columns of cells. So the correct way to iterate is:

for each_column in cell_range:
    for cell in each_column :
        cell.value = 2

The reason cell = 2 doesn't work is that assignment makes names refer to objects. Before the assignment the name cell referred to one of the cells in cell_range . Afterwords, the name cell referred to integer object 2 . The cell object referred to by the name cell is unaffected by this assignment.

But if this is true why does ws['A4'] = 4 work? That's because ws['A4'] = 4 is not assignment! It's actually syntactic sugar for a method call ws.__setitem__('A4', 4) . Because it's a method call it can actually mutate an object rather than just make a name refer to an object as in normal assignment.

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