簡體   English   中英

python:將數據框更新到現有的excel工作表,而不會覆蓋同一工作表和其他工作表上的內容

[英]python: update dataframe to existing excel sheet without overwriting contents on the same sheet and other sheets

奮斗了幾個小時,所以我決定在這里尋求專家的幫助:

我想修改現有的Excel工作表而不覆蓋內容。 我在此excel文件中還有其他工作表,並且我不想影響其他工作表。

我已經創建了示例代碼,但是不確定如何添加我想保留的第二張表。

t=pd.date_range('2004-01-31', freq='M', periods=4)
first=pd.DataFrame({'A':[1,1,1,1],
             'B':[2,2,2,2]}, index=t)
first.index=first.index.strftime('%Y-%m-%d')
writer=pd.ExcelWriter('test.xlsx')
first.to_excel(writer, sheet_name='Here')
first.to_excel(writer, sheet_name='Keep')

#how to update the sheet'Here', cell A5:C6 with following without overwriting the rest?
#I want to keep the sheet "Keep"
update=pd.DataFrame({'A':[3,4],
                     'B':[4,5]}, index=pd.date_range('2004-04-30', 
                                                     periods=2,
                                                     freq='M'))

我已經研究過了。 但不確定如何將數據框寫入工作表。

我嘗試過的示例:

import openpyxl
xfile = openpyxl.load_workbook('test.xlsx')
sheet = xfile.get_sheet_by_name('test')
sheet['B5']='wrote!!'
xfile.save('test2.xlsx')

我自己弄清楚了:

#Prepare the excel we want to write to
t=pd.date_range('2004-01-31', freq='M', periods=4)
first=pd.DataFrame({'A':[1,1,1,1],
             'B':[2,2,2,2]}, index=t)
first.index=first.index.strftime('%Y-%m-%d')
writer=pd.ExcelWriter('test.xlsx')
first.to_excel(writer, sheet_name='Here')
first.to_excel(writer, sheet_name='Keep')

#read the existing sheets so that openpyxl won't create a new one later
book = load_workbook('test.xlsx')
writer = pandas.ExcelWriter('test.xlsx', engine='openpyxl') 
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

#update without overwrites
update=pd.DataFrame({'A':[3,4],
                     'B':[4,5]}, index=(pd.date_range('2004-04-30', 
                                                     periods=2,
                                                     freq='M').strftime('%Y-%m-%d')))

update.to_excel(writer, "Here", startrow=1, startcol=2)

writer.save()

我建議您將openpyxl更新為2.4(測試版或簽出版本),並使用內置的支持來回數據框。 這些現在可以通過openypxl輕松轉換為您要執行的操作。

有關詳細信息,請參見http://openpyxl.readthedocs.io/en/latest/pandas.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM