向已有的excel表中追加数据存储(表头一致)

在使用Pandas处理Excel文件时,如果需要在已有的Excel文件中向下添加新数据,可以使用 openpyxl 作为引擎来实现这一功能。下面是具体的步骤和代码示例:

  1. 读取已有的Excel文件:使用 pd.read_excel 读取已有的Excel文件和数据。
  2. 准备新数据:将新数据整理为DataFrame。
  3. 将新数据追加到已有的数据中:通过 pd.concat 将新数据和已有的数据进行合并。
  4. 将合并后的数据写回到Excel文件中:使用 pd.ExcelWriteropenpyxl 引擎将数据写回到Excel文件中。
import pandas as pd
from openpyxl import load_workbook

# 读取已有的Excel文件
file_path = 'existing_file.xlsx'
existing_data = pd.read_excel(file_path, sheet_name='Sheet1')

# 新的数据
new_data = {
    'Column1': [value1, value2, value3],
    'Column2': [value4, value5, value6],
    # 添加更多列和数据
}

new_df = pd.DataFrame(new_data)

# 将新数据追加到已有的数据中
combined_data = pd.concat([existing_data, new_df], ignore_index=True)
# combined_data.index = ...

# 将合并后的数据写回到Excel文件中
with pd.ExcelWriter(file_path, engine='openpyxl', mode='a', if_sheet_exists='overlay') as writer:
    combined_data.to_excel(writer, sheet_name='Sheet1', index=False)

print("Data has been appended successfully.")

代码解读:

读取已有的Excel文件

existing_data = pd.read_excel(file_path, sheet_name='Sheet1')

这一步读取了名为 existing_file.xlsx 的Excel文件中的 Sheet1 表,并将其存储在 existing_data DataFrame 中。

准备新数据

new_data = {
    'Column1': [value1, value2, value3],
    'Column2': [value4, value5, value6],
    # 添加更多列和数据
}
new_df = pd.DataFrame(new_data)

将新数据组织成字典形式,并转换为DataFrame。

合并数据

combined_data = pd.concat([existing_data, new_df], ignore_index=True)

使用 pd.concat 将新数据和已有数据进行合并。ignore_index=True 参数确保索引被重置。

写回Excel文件

with pd.ExcelWriter(file_path, engine='openpyxl', mode='a', if_sheet_exists='overlay') as writer:
    combined_data.to_excel(writer, sheet_name='Sheet1', index=False)

使用 pd.ExcelWriter 将合并后的数据写回原Excel文件中。engine='openpyxl' 指定了使用openpyxl引擎,mode='a' 表示追加模式,if_sheet_exists='overlay' 表示如果工作表存在则覆盖写入。

官方链接:

https://pandas.pydata.org/docs/reference/api/pandas.ExcelWriter.html

mode, default ‘w’

File mode to use (write or append). Append does not work with fsspec URLs.

if_sheet_exists, default ‘error’

How to behave when trying to write to a sheet that already exists (append mode only).

  • error: raise a ValueError.
  • new: Create a new sheet, with a name determined by the engine.
  • replace: Delete the contents of the sheet before writing to it.
  • overlay: Write contents to the existing sheet without first removing, but possibly over top of, the existing contents.
posted @ 2024-06-22 13:46  Amiyai  阅读(37)  评论(0编辑  收藏  举报