Issue
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:
Into this:
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")
Answered By - 0x00
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.