[英]Using pandas in Python to loop through Worksheets updating a range of cells
我正在嘗試獲取工作簿,遍歷特定工作表檢索數據框,對其進行操作並將數據框粘貼回同一位置,而不更改文檔中的任何其他數據/工作表,這就是我正在嘗試的:
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)
盡管我不確定當文件已經存在並且您覆蓋其中一些文件時它將如何表現。 首先閱讀所有內容,操作所需的工作表並保存到新文件可能更容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.