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.
JavaScript
x
22
22
1
import openpyxl
2
3
roster = openpyxl.load_workbook('Path/To/File/roster.xlsx')
4
sheet = roster.active
5
6
counter = 7
7
while counter < 1000:
8
counter +=1
9
fname = input("Enter first name: ").capitalize().strip()
10
lname = input("Enter last name: ").capitalize().strip()
11
grade = int(input("Enter grade: "))
12
attendance = int(input("Enter atendance: "))
13
14
for row in sheet.rows:
15
sheet[f'A{counter}'] = f'{counter}'
16
sheet[f'B{counter}'] = fname
17
sheet[f'C{counter}'] = lname
18
sheet[f'D{counter}'] = grade
19
sheet[f'E{counter}'] = attendance
20
21
roster.save('Path/To/File/roster.xlsx')
22
Advertisement
Answer
You can use max_row
and append from openpyxl.worksheet.
JavaScript
1
10
10
1
counter = sheet.max_row
2
while counter < 1000:
3
fname = input("Enter first name: ").capitalize().strip()
4
lname = input("Enter last name: ").capitalize().strip()
5
grade = int(input("Enter grade: "))
6
attendance = int(input("Enter atendance: "))
7
8
sheet.append([counter, fname, lname, grade, attendance])
9
counter += 1
10