Python Openpyxl iter_rows and add defined value in each cell

Question:

Question: Can someone please let me know how I can achieve the following task:

I’ve defined the column, but i need a specific value to go into each cell within that column.

Also, if column 6 only has x amount of rows, then i want column 7 to also have only x amount of rows with the values pasted in it.

This is the code i’ve tried.

import openpyxl

wb = openpyxl.load_workbook(filename=r'C:Users.spyder-py3dataBMA.xlsx')
ws = wb.worksheets[0]
for row in ws.iter_rows('G{}:G{}'.format(ws.min_row,ws.max_row)):
    for cell in row:
        ws.cell(row=cell, column=7).value = 'BMA'
wb.save(r'C:Users.spyder-py3dataBMA.csv')
wb.close()
Asked By: Yousuf

||

Answers:

I figured out most of the issue by looking at this answer:

https://stackoverflow.com/a/15004956/9649146

This is the code i end up with:

import openpyxl

wb = openpyxl.load_workbook(filename=r'C:Users.spyder-py3dataAAXN.xlsx')
ws = wb.worksheets[0]
r = 2
for row in ws.iter_rows('G{}:G{}'.format(ws.min_row,ws.max_row)):
    for cell in row:
        ws.cell(row=r, column=7).value = 'AAXN'
        r += 1
wb.save(r'C:Users.spyder-py3dataAAXN.csv')
wb.close()
Answered By: Yousuf

Or, you can do something like this:

for row in filesheet.iter_rows(min_row=2, max_row=file_sheet.max_row):
filesheet.cell(row=row[0].row, column=7).value = 'my value'
Answered By: cdrrr
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.