我一直在try 更新现有Excel中的数据--过程如下:

1)从Excel中读取数据

2)使用Pandas 将其与新数据相结合

3)将合并后的数据帧保存到原始文件中

它一直返回以下错误,我认为这是因为在读取相同的文件时写入(更新)了该文件:

AttributeError                            Traceback (most recent call last)
Cell In[14], line 19
     18 with pd.ExcelWriter(file_path, engine='openpyxl') as writer:
---> 19     writer.book = book
     20     writer.sheets = {ws.title: ws for ws in book.worksheets}

AttributeError: property 'book' of 'OpenpyxlWriter' object has no setter

我的代码如下--运行它还会擦除原始文件的数据,并使该文件不可用:

# Load the Excel file
file_path = 'original.xlsx'
update = 'update.xlsx'

# Open the file in read-only mode to prevent any locks
with open(file_path, "rb") as file:
    book = load_workbook(file)

# Combine original with update file
for sheet_name in ['sheet1', ...]:
    df1 = pd.read_excel(file_path, sheet_name = sheet_name)
    df2 = pd.read_excel(update, sheet_name = sheet_name)
    df2 = df2.iloc[::-1]
    df1 = pd.concat([df1, df2], ignore_index = True)
    df1 = df1.drop_duplicates(subset = 'column1', keep = 'last')

    # Write combined data to the sheet
    with pd.ExcelWriter(file_path, engine='openpyxl') as writer:
        writer.book = book
        writer.sheets = {ws.title: ws for ws in book.worksheets}
        
        # Set the sheet as the active sheet
        book.active = book.sheetnames.index(sheet_name)
        
        df1.to_excel(writer, sheet_name = sheet_name, index = False, startrow = 1)

    print(f"Successfully updated '{sheet_name}' sheet in '{file_path}'.")

推荐答案

这是因为book等于read-only property.

由于您只更新一个文件,您可以try 使用Pandas:docs提供的带有标志aif_sheet_exists的追加模式

结果将类似于:

# Combine original with update file
for sheet_name in ['sheet1', 'sheet2']:
    df1 = pd.read_excel(file_path, sheet_name=sheet_name)
    df2 = pd.read_excel(update, sheet_name=sheet_name)
    df2 = df2.iloc[::-1]
    df1 = pd.concat([df1, df2], ignore_index=True)
    df1 = df1.drop_duplicates(subset='column1', keep='last')

    # Write combined data to the sheet
    with pd.ExcelWriter(file_path, mode='a', if_sheet_exists='replace', engine='openpyxl') as writer:
        df1.to_excel(writer, sheet_name=sheet_name, index=False, startrow=0)

    print(f"Successfully updated '{sheet_name}' sheet in '{file_path}'.")

Python相关问答推荐

当测试字符串100%包含查询字符串时,为什么t fuzzywuzzy s Process.extractBests不给出100%分数?

将numpy数组与空数组相加

创建带有二维码的Flask应用程序,可重定向到特定端点

从管道将Python应用程序部署到Azure Web应用程序,不包括需求包

如何用symy更新分段函数

将HTML输出转换为表格中的问题

如何在Deliveryter笔记本中从同步上下文正确地安排和等待Delivercio代码中的结果?

Pythind 11无法弄清楚如何访问tuple元素

运行回文查找器代码时发生错误:[类型错误:builtin_index_or_system对象不可订阅]

大Pandas 胚胎中产生组合

Pandas实际上如何对基于自定义的索引(integer和非integer)执行索引

如何比较numPy数组中的两个图像以获取它们不同的像素

图像 pyramid .难以创建所需的合成图像

将pandas Dataframe转换为3D numpy矩阵

如何使用表达式将字符串解压缩到Polars DataFrame中的多个列中?

多指标不同顺序串联大Pandas 模型

mypy无法推断类型参数.List和Iterable的区别

使用Python从URL下载Excel文件

Maya Python脚本将纹理应用于所有对象,而不是选定对象

当HTTP 201响应包含 Big Data 的POST请求时,应该是什么?