如何使用 openpyxl python 将指定行的数据附加到 excel 文件?

how to append data using openpyxl python to excel file from a specified row?

我有不同的 Python 列表变量(data1、data2、data3 等),其中包含我想放入现有 excel sheet 中的数据。目前我的循环是这样的。

for row, entry in enumerate(data1,start=1):
  st.cell(row=row, column=1, value=entry)
  work.save('sample.xlsx')
for row, entry in enumerate(data2,start=1):
  st.cell(row=row, column=2, value=entry)
  work.save('sample.xlsx')
for row, entry in enumerate(data3,start=1):
  st.cell(row=row, column=3, value=entry)
  work.save('sample.xlsx')
for row, entry in enumerate(data4,start=1):
  st.cell(row=row, column=4, value=entry)
  work.save('sample.xlsx')
for row, entry in enumerate(data5,start=1):
  st.cell(row=row, column=5, value=entry)
  work.save('sample.xlsx')
for row, entry in enumerate(data6,start=1):
  st.cell(row=row, column=6, value=entry)
  work.save('sample.xlsx')
for row, entry in enumerate(data7,start=1):
  st.cell(row=row, column=7, value=entry)
  work.save('sample.xlsx')      

一旦我的 Python 脚本运行,它将存储第一行的数据。 如果我又是运行我希望新数据低于可用数据的脚本

怎么做?

尝试使用:

sheet.max_row 

它将 return 最后一行值,您可以从那里开始写入新值:

max = ws.max_row
for row, entry in enumerate(data1, start=1):
   st.cell(row=row+max, column=1, value=entry)

ws.append() 将始终在任何现有数据下方添加行。

openpyxl 有许多不同的方法来精确,但 ws.append 在以前的答案中足以满足您的要求。假设您已将数据写入新的 sample.xlsx:

from openpyxl.workbook import Workbook

headers       = ['Company','Address','Tel','Web']
workbook_name = 'sample.xlsx'
wb = Workbook()
page = wb.active
page.title = 'companies'
page.append(headers) # write the headers to the first line

# Data to write:
companies = [['name1','address1','tel1','web1'], ['name2','address2','tel2','web2']]

for info in companies:
    page.append(info)
wb.save(filename = workbook_name)

现在,要追加新行,您必须先使用 load_workbook:

打开现有书籍
from openpyxl import load_workbook

workbook_name = 'sample.xlsx'
wb = load_workbook(workbook_name)
page = wb.active

# New data to write:
new_companies = [['name3','address3','tel3','web3'], ['name4','address4','tel4','web4']]

for info in new_companies:
    page.append(info)

wb.save(filename=workbook_name)

您可以使用 append() 方法将值附加到现有 excel 文件。 示例:

workbook_obj = openpyxl.load_workbook(excelFilePath)
sheet_obj = workbook_obj.active
col1 = 'NewValueCol1'
col2 = 'NewValueCol2'
sheet_obj.append([col1, col2])
workbook_obj.save(excelFilePath)

此处 col1 和 col2 值将与 excel sheet 中的现有数据相加。