简体   繁体   中英

How to append data to the last row (every time) of an Excel file?

I am looking for a way to append data from a Python program to an excel sheet. For this, I chose the openpyxl library to save this data.

My problem is how to put new data in the excel file without losing the current data, in the last row of the sheet. I look into the documentation but I did not see any answer.

I do not know if this library has a method to add new data or I need to make a logic to this task.

What you're looking for is the Worksheet.append method:

Appends a group of values at the bottom of the current sheet.

  • If it's a list: all values are added in order, starting from the first column
  • If it's a dict: values are assigned to the columns indicated by the keys (numbers or letters)

So no need to check for the last row. Just use this method to always add the data at the end.

ws.append(["some", "test", "data"])

The last row of the sheet can be found using max_row():

from openpyxl import load_workbook

myFileName=r'C:\DemoFile.xlsx'
#load the workbook, and put the sheet into a variable
wb = load_workbook(filename=myFileName)
ws = wb['Sheet1']

#max_row is a sheet function that gets the last row in a sheet.
newRowLocation = ws.max_row +1

#write to the cell you want, specifying row and column, and value :-)
ws.cell(column=1,row=newRowLocation, value="aha! a new entry at the end")
wb.save(filename=myFileName)
wb.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM