删除并替换 Excel sheet 中的 Pandas DataFrame

Remove and replace Pandas DataFrame in Excel sheet

我将 pandas DataFrame 存储在 Excel sheet 中。当我重新 运行 我的代码时,我希望 sheet 完全被覆盖。这很重要,因为我的代码多次写入同一个文件,即在不同时刻加载和保存某些 sheet,不想打扰当前未更改的 sheet。因此,如果代码的新迭代产生更少的行或列,旧数据仍将存在。例如,如果迭代 #1 产生 500 行但迭代 #2 仅产生 499,则第 500 行仍将显示在我的 Excel 文件中。

我知道我可以遍历所有单元格并将它们的值设置为 None,但我认为完全 remove 给定的 sheet 会更有效, create_sheet 用相同的 sheet 名称,然后将我的 DataFrame 保存到新的 sheet。下面的代码是我正在尝试做的 MRE。它成功删除了 sheet,创建了一个新文件,并保存了文件,但 to_excel 似乎没有执行。生成的 Excel 文件具有 'test' sheet,但它是空白的。

import pandas as pd
import numpy as np
import openpyxl
from openpyxl import load_workbook
from openpyxl import Workbook

df_data = {'A': np.random.randint(1, 50, 20),
            'B': np.random.randint(1, 50, 20),
            'C': np.random.randint(1, 50, 20),
            'D': np.random.randint(1, 50, 20)}

df = pd.DataFrame(data=df_data)

fn = 'test.xlsx'
sheet = 'test'
df.to_excel(fn, sheet_name=sheet)

df2 = pd.read_excel(fn, sheet_name=sheet, index_col=0)
df2.drop(columns=['A'], inplace=True)

book = load_workbook(fn)
writer = pd.ExcelWriter(fn, engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
s = book[sheet]
book.remove(s)
book.create_sheet(sheet, 0)

#THIS CODE WILL ACTUALLY WRITE TO THE SHEET, BUT df2 WILL NOT
#s2 = book[sheet]
#s2['A1'] = 'This will write to the sheet'

df2.to_excel(writer, sheet_name=sheet)
writer.save()

请注意,如果未注释,我的注释代码将写入正确的 sheet。似乎只是 to_excel 行不起作用。

您可以使用一个函数来做到这一点:

import pandas as pd

def write2excel(filename,sheetname,dataframe):
    with pd.ExcelWriter(filename, engine='openpyxl', mode='a') as writer: 
        workBook = writer.book
        try:
            workBook.remove(workBook[sheetname])
        except:
            print("There is no such sheet in this file")
        finally:
            dataframe.to_excel(writer, sheet_name=sheetname,index=False)
            writer.save()

在此之后,假设您有一个数据帧 df、一个工作簿 Myfile.xlsx 和您要覆盖的 sheet THE_sheet do

write2excel('Myfile.xlsx','THE_sheet',df)