[英]How to add Pandas dataframe to an existing xlsx file using to_excel
我已經使用xlsxwriter
將一些內容寫入 xlsx 文件
workbook = xlsxwriter.Workbook(file_name)
worksheet = workbook.add_worksheet()
worksheet.write(row, col, value)
worksheet.close()
我想通過 to_excel 在現有行之后添加一個to_excel
df.to_excel(file_name,
startrow=len(existing_content),
engine='xlsxwriter')
但是,這似乎不起作用。dataframe 未插入到文件中。 任何人都知道為什么?
遺憾的是,由於上面的內容不是專門寫的,我們以to_excel和XlsxWriter為例來看一下。
使用 xlsxwriter
import xlsxwriter
# Create a new Excel file and add a worksheet
workbook = xlsxwriter.Workbook('example.xlsx')
worksheet = workbook.add_worksheet()
# Add some data to the worksheet
worksheet.write('A1', 'Language')
worksheet.write('B1', 'Score')
worksheet.write('A2', 'Python')
worksheet.write('B2', 100)
worksheet.write('A3', 'Java')
worksheet.write('B3', 98)
worksheet.write('A4', 'Ruby')
worksheet.write('B4', 88)
# Save the file
workbook.close()
使用上面的代碼,我們將類似於下面的表格保存到 Excel 文件中。
語言 | 分數 |
---|---|
Python | 100 |
Java | 98 |
Ruby | 88 |
接下來,如果我們想使用 dataframe.to_excel 添加行:
使用 to_excel
import pandas as pd
# Load an existing Excel file
existing_file = pd.read_excel('example.xlsx')
# Create a new DataFrame to append
df = pd.DataFrame({
'Language': ['C++', 'Javascript', 'C#'],
'Score': [78, 97, 67]
})
# Append the new DataFrame to the existing file
result = pd.concat([existing_file, df])
# Write the combined DataFrame to the existing file
result.to_excel('example.xlsx', index=False)
使用pandas concat的原因:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.