I want to find the next empty cell in a specific column and write to values that cell. I've tried it using following method:
for row in sheet['A{}:A{}'.format(sheet.min_row,sheet.max_row)]:if row is None:sheet.cell(column=1).value = nameelse:print ("Cell have data")
But It's not writing data to next empty cell. How can I fix that?
It's pretty pointless to construct a string with min_row
and max_row
. You can simply access the whole column:
from openpyxl import load_workbookwb = load_workbook("book.xlsx")
ws = wb.activefor cell in ws["A"]:if cell.value is None:cell.value = "new value2"wb.save("book.xlsx")
But this reads the whole column at once as a tuple. Instead, you can use iter_rows()
(iter_cols()
is not available in read-only):
from openpyxl import load_workbookwb = load_workbook("book.xlsx")
ws = wb.activefor row in ws.iter_rows(min_col=1, max_col=1):cell = row[0]if cell.value is None:cell.value = "new value"wb.save("book.xlsx")