在Python中使用pandas循环遍历工作表以更新单元格范围



我试图采取一个工作簿,循环通过特定的工作表检索一个数据框,操纵它,基本上粘贴数据框回到同一个地方,而不改变文档中的任何其他数据/表,这就是我正在尝试的:

path= '<folder location>.xlsx'
wb = pd.ExcelFile(path)
for sht in ['sheet1','sheet2','sheet3']:
df= pd.read_excel(wb,sheet_name = sht, skiprows = 607,nrows = 11, usecols = range(2,15))
# here I manipulate the df, to then save it down in the same place
df.to_excel(wb,sheet_name = sht, startcol=3, startrow=607)
# Save down file
wb.save(path))
wb.close()

到目前为止,我的解决方案将只保存第一个工作表,只有我操作的数据,我丢失了所有其他的工作表和数据,我想留在工作表上,所以我最终只得到sheet1,只有我操作的数据。

非常感谢您的帮助,谢谢。

尝试使用ExcelWriter代替ExcelFile:

path= 'folder location.xlsx'
with pd.ExcelWriter(path) as writer:   
for sht in ['sheet1','sheet2','sheet3']:
df= pd.read_excel(wb,sheet_name = sht, skiprows = 607,nrows = 11, usecols = range(2,15))
####here I manipulate the df, to then save it down in the same place###
df.to_excel(writer,sheet_name = sht, startcol=3, startrow=607)

虽然我不确定当文件已经存在并且您覆盖其中一些文件时它将如何表现。首先阅读所有内容,操作所需的表格并保存到新文件可能会更容易。

最新更新