Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Openpyxl – Offset using cell value from above

I want to iterate down a column and if I find an empty cell, use the value from the cell above.

I want to turn this:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Into this:

enter image description here

I’m using offset but I can only list the values from below the current cell.

from openpyxl import load_workbook
import openpyxl

wb = load_workbook("original-workbook.xlsx")
ws = wb["Sheet1"]

for row in ws.iter_rows(min_row=1, max_col=3):
    if row[0].value and row[0].value.startswith("Microsoft"):
        print("Ocupado!")
    else:
        row[0].value = row[0].offset(row=1, column=0).value

wb.save("new-improved-workbook.xlsx")

Is there an alternative?

Thanks in advance

>Solution :

You are close. You were able to find if a cell had content or not. All you need to do is save that content into a variable so when a cell is empty you put the saved value in it.

from openpyxl import load_workbook

wb = load_workbook("original-workbook.xlsx")
ws = wb["Sheet1"]

for row in ws.iter_rows(min_row=1, max_col=3):
    if row[0].value and row[0].value.startswith("Microsoft"):
        saved_value = row[0].value
        print("Ocupado!")
    else:
        row[0].value = saved_value

wb.save("new-improved-workbook.xlsx")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading