繁体   English   中英

如何使用 to_excel 将 Pandas dataframe 添加到现有的 xlsx 文件

[英]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的原因:

  • 到append,需要使用pandas.DataFrame.ExcelWriter(),但是XlsxWriter在ExcelWriter中不支持append模式
  • 虽然可以使用 pandas.DataFrame.append() 来完成任务,但 append 方法计划在未来被删除,因此我们使用 concat 代替。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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