Pandas:如果工作表存在,则“替换”不工作

2024-04-20 12:06:28 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码:

def save_excel_sheet(df, filepath, sheetname, index=False):
    # Create file if it does not exist
    if not os.path.exists(filepath):
        df.to_excel(filepath, sheet_name=sheetname, index=index)

    # Otherwise, add a sheet. Overwrite if there exists one with the same name.
    else:
        with pd.ExcelWriter(filepath, engine='openpyxl', if_sheet_exists='replace', mode='a') as writer:
            df.to_excel(writer, sheet_name=sheetname, index=index)

预期的行为是,当调用现有文件上的函数时,使用名为“sheetname”的现有工作表,它应该替换/覆盖该工作表。 但它不起作用。它只创建sheetname、sheetname1、sheetname2。。。 我尝试将模式设置为“w”,但它会覆盖任何其他现有图纸,我希望保留这些图纸

我该怎么办? 谢谢