简体   繁体   English

如何将数据附加到 Excel 文件的最后一行(每次)?

[英]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.我正在寻找一种将 Python 程序中的数据附加到 Excel 工作表的方法。 For this, I chose the openpyxl library to save this data.为此,我选择了 openpyxl 库来保存这些数据。

My problem is how to put new data in the excel file without losing the current data, in the last row of the sheet.我的问题是如何在不丢失当前数据的情况下将新数据放入 Excel 文件中,在工作表的最后一行。 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:您正在寻找的是Worksheet.append方法:

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():可以使用 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.

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