Skip to content
Advertisement

How to write to new empty cell in openpyxl

I see there are a few similar questions already asked, but none seem to solve my problem. Also, some offer deprecated solutions such as using coordinate.

The code I have works fine, but because I start the loop at a certain position, every time I re-run the code, it obviously starts writing from that one position. I’m looking for the most pythonic and up-to-date solution to this.

Thanks in advance for your time and help.

import openpyxl

roster = openpyxl.load_workbook('Path/To/File/roster.xlsx')
sheet = roster.active

counter = 7
while counter < 1000:
    counter +=1
    fname = input("Enter first name: ").capitalize().strip()
    lname = input("Enter last name: ").capitalize().strip()
    grade = int(input("Enter grade: "))
    attendance = int(input("Enter atendance: "))

    for row in sheet.rows:
        sheet[f'A{counter}'] = f'{counter}'
        sheet[f'B{counter}'] = fname
        sheet[f'C{counter}'] = lname
        sheet[f'D{counter}'] = grade
        sheet[f'E{counter}'] = attendance

roster.save('Path/To/File/roster.xlsx')

Advertisement

Answer

You can use max_row and append from openpyxl.worksheet.

counter = sheet.max_row
while counter < 1000:
    fname = input("Enter first name: ").capitalize().strip()
    lname = input("Enter last name: ").capitalize().strip()
    grade = int(input("Enter grade: "))
    attendance = int(input("Enter atendance: "))

    sheet.append([counter, fname, lname, grade, attendance])
    counter += 1
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement