使用openpyxl在excel表的最后一行添加数据



我试图将用户的几个数据添加到几个列的最后一行,我使用了以下方法:

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)

当我应用这个时,我得到一个错误,它在每个新列的下一行打印数据,如下所示:

Excel数据表照片

可能最简单的方法就是创建一个列表并追加。

...
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)

最新更新