如何使用数据框中的数据更新 Excel 工作表,具有不同的列长度,并仍保留 Excel 工作表中的现有函数

问题描述 投票:0回答:1

假设我有一个包含多列 (+60) 的 Excel 电子表格,其中一些包含函数,一些包含数字。然后我有一个包含三列的数据框,它们通常比电子表格中的列长。

我希望加入/合并/组合这些,以便我的数据框具有三列“覆盖”电子表格中的三列,但不删除电子表格中的函数或其他数据。

我尝试过使用 pandas 和不同的连接,但最终电子表格中没有我的函数。我也研究过 openpyxl,但到目前为止还没有运气。三个列名可以相同也可以不同,没关系。

我尝试过在 pandas、openpyxl、join 中使用不同的函数

python pandas excel dataframe openpyxl
1个回答
0
投票

如果您想保留原始电子表格中的公式,同时只更新某些列,则不能直接使用“pandas”。它不会保留 Excel 特定的功能,例如公式。相反,您可以使用“openpyxl”直接与 Excel 文件交互。像这样:

import pandas as pd
from openpyxl import load_workbook

# Your dataframe, for example:
df = pd.DataFrame({
    'ColA': [1, 2, 3],
    'ColB': [4, 5, 6],
    'ColC': [7, 8, 9]
})

# Load your Excel file
book = load_workbook('path_to_excel.xlsx')

# Select the active worksheet (or specify the sheet name)
writer = pd.ExcelWriter('path_to_excel.xlsx', engine='openpyxl') 
writer.book = book

# Overwrite just the necessary columns. Here, we're updating columns A, B, and C.
# You can adjust the range as required.
for index, value in enumerate(df['ColA']):
    book.active.cell(row=index + 2, column=1, value=value) # +2 as Excel is 1-based and we're skipping header

for index, value in enumerate(df['ColB']):
    book.active.cell(row=index + 2, column=2, value=value)

for index, value in enumerate(df['ColC']):
    book.active.cell(row=index + 2, column=3, value=value)

# Save the workbook
writer.save()

在这里,我们仅更新要更新的列的单元格,因此其他单元格中的公式不受影响。如果您想要考虑标题和/或从 Excel 工作表顶部偏移行,请确保调整循环范围(+2 部分)。

© www.soinside.com 2019 - 2024. All rights reserved.