简体   繁体   中英

Replace the data in an excel sheet

I have an excel file of 10 sheets named like A1, A2, ... A10. I would like to replace the contents of sheet A2 by a new pandas dataframe. I dont find any function for such a transformation.

Is there any workaround available for this?

import pandas
from openpyxl import load_workbook

df = pandas.DataFrame() # your dataframe

book = load_workbook('your_excel')
writer = pandas.ExcelWriter('your_excel', engine='openpyxl')
writer.book = book

idx=book.sheetnames.index('A2')
book.remove(book.worksheets[idx])
book.create_sheet('A2',idx)

writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

df.to_excel(writer, "A2",index=0,startrow=0,startcol=0)
writer.save()

Try this code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM