[英]How to append data to the last row (every time) of an Excel file?
我正在尋找一種將 Python 程序中的數據附加到 Excel 工作表的方法。 為此,我選擇了 openpyxl 庫來保存這些數據。
我的問題是如何在不丟失當前數據的情況下將新數據放入 Excel 文件中,在工作表的最后一行。 我查看了文檔,但沒有看到任何答案。
我不知道這個庫是否有添加新數據的方法,或者我需要為此任務制定邏輯。
您正在尋找的是Worksheet.append
方法:
在當前工作表的底部附加一組值。
- 如果是列表:從第一列開始按順序添加所有值
- 如果是字典:將值分配給鍵(數字或字母)指示的列
所以不需要檢查最后一行。 只需使用此方法始終在最后添加數據。
ws.append(["some", "test", "data"])
可以使用 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.