将数据框更新到现有的excel工作表

将数据框更新到现有的excel工作表

本文介绍了python:将数据框更新到现有的excel工作表,而不会覆盖同一工作表和其他工作表上的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为此奋斗了几个小时,所以我决定在这里寻求专家的帮助:

Struggling for this for hours so I decided to ask for help from experts here:

我想修改现有的Excel工作表而不覆盖内容.我在此excel文件中还有其他工作表,并且我不想影响其他工作表.

I want to modify existing excel sheet without overwriting content.I have other sheets in this excel file and I don't want to impact other sheets.

我已经创建了示例代码,不确定如何添加我想保留的第二张纸.

I've created sample code, not sure how to add the second sheet that I want to keep though.

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

我已经研究过.但不确定如何将数据框写入工作表中.

I've researched SO. But not sure how to write a dataframe into the sheet.

我尝试过的示例:

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

这篇关于python:将数据框更新到现有的excel工作表,而不会覆盖同一工作表和其他工作表上的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 03:48