Home > OS >  Adding data in last row of excel sheet using openpyxl
Adding data in last row of excel sheet using openpyxl

Time:09-18

I am trying to add several data from user to the last rows of several columns, i used this method:

            firstname=  input("enter your first name: ")
            lastname= input("enter your last name: ")
            newpass = input("enter a password: ")
            newbalance = input("enter balance: ")
            ws.cell(column=1,row=ws.max_row  1, value=firstname)
            ws.cell(column=2,row=ws.max_row  1, value=lastname)
            ws.cell(column=4,row=ws.max_row  1, value=newpass)
            ws.cell(column=5,row=ws.max_row  1, value=newbalance)
            wd.save(filename)

when i apply this i get an error that it prints the data at the next row of each new column, like this:

The Excel data sheet photo

CodePudding user response:

Possibly the easiest is to just create a list and append.

...
firstname=  input("enter your first name: ")
lastname= input("enter your last name: ")
newpass = input("enter a password: ")
# newbalance = input("enter balance: ")
# May want to cast 'newbalance' to int (or float) and maybe want to do cast int for newpass based on your example sheet
newbalance = int(input("enter balance: "))
# ws.cell(column=1,row=ws.max_row  1, value=firstname)
# ws.cell(column=2,row=ws.max_row  1, value=lastname)
# ws.cell(column=4,row=ws.max_row  1, value=newpass)
# ws.cell(column=5,row=ws.max_row  1, value=newbalance)
# Create a list with values including string for column 3
list_append = [firstname, lastname, '', newpass, newbalance]
# 'append' will add the list to the last row of the sheet starting at the first column
ws.append(list_append)
wd.save(filename)
  • Related