pandas to_excel 添加一个新的工作表到存在的excel文件中

Every time you want to save a Pandas DataFrame to an Excel, you may call this function:

import os

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)
posted @ 2023-12-22 16:06  Oops!#  阅读(29)  评论(0编辑  收藏  举报