为什么 if_sheet_exists='replace' 创建新的 excel sheet。当 df 导出到现有 excel sheet

Why if_sheet_exists='replace' creating new excel sheet. while df exporting to a existing excel sheet

我正在尝试将 df 值导出到 excel 文件而不影响其他 sheet。但上面的代码正在创建一个新的 sheet 而不是替换现有的 sheet。有人可以帮忙吗?

这是我的代码

import pandas as pd
import openpyxl

df1 = pd.read_excel(r'D:\FY 22 - 23\Apr - 22\Daily Sales\Daily_level_data.xlsx',sheet_name = 'test')

with pd.ExcelWriter(r'D:\FY 22 - 23\Apr - 22\Daily Sales\Daily Sales Master_test.xlsx', mode="a",
                    engine="openpyxl", on_sheet_exists ="replace") as writer:
    df1.to_excel(writer, sheet_name="Day_level")
    

print('data  imported in daily sales master - sucessfully')

好吧,看看文档,应该是 if_sheet_exists 而不是 on_sheet_exists。但是,它仍然无法正常工作。

您可以使用 writer.sheets 将表格传递给作者。有点烦人,但它有效:

import pandas as pd
import openpyxl

book = openpyxl.load_workbook(r'D:\FY 22 - 23\Apr - 22\Daily Sales\Daily Sales Master_test1.xlsx')
df1 = pd.read_excel(r'D:\FY 22 - 23\Apr - 22\Daily Sales\Daily_level_data.xlsx',sheet_name = 'test')

with pd.ExcelWriter(r'D:\FY 22 - 23\Apr - 22\Daily Sales\Daily Sales Master_test1.xlsx', mode="a",
                    engine="openpyxl", ) as writer:
    writer.book = book
    writer.sheets = {ws.title:ws for ws in book.worksheets}
    df1.to_excel(writer, sheet_name="Day_level")
    

print('data  imported in daily sales master - sucessfully')