删除并替换Excel工作表中的Pandas DataFrame



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

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

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()

请注意,如果取消注释,我的注释代码将写入正确的工作表。似乎只是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和要覆盖THE_sheet的工作表进行

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

最新更新