python:将数据帧更新为现有 excel sheet,而不覆盖相同 sheet 和其他 sheet 上的内容

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

为此苦苦挣扎了几个小时,所以我决定在这里向专家寻求帮助:

我想修改现有的 excel sheet 而不覆盖内容。 我在这个 excel 文件中还有其他 sheet,我不想影响其他 sheet。

我已经创建了示例代码,但不确定如何添加我想保留的第二个 sheet。

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

我研究过 SO。但不确定如何将数据帧写入 sheet.

我试过的例子:

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

我建议您更新到 openpyxl 的 2.4(测试版或结帐版)并使用内置的数据帧支持。这些现在可以很容易地由 openypxl 转换成你想做的行。

详情见http://openpyxl.readthedocs.io/en/latest/pandas.html

自己想出来的:

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