How to overwrite data on an existing excel sheet while preserving all other sheets?

前端 未结 1 1481
悲&欢浪女
悲&欢浪女 2020-12-19 10:48

I have a pandas dataframe df which I want to overwrite to a sheet Data of an excel file while preserving all the other sheets since other sheets ha

相关标签:
1条回答
  • 2020-12-19 11:15

    You can do it using openpyxl:

    import pandas as pd
    from openpyxl import load_workbook
    
    book = load_workbook(filename)
    writer = pd.ExcelWriter(filename, engine='openpyxl') 
    writer.book = book
    
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
    
    df.to_excel(writer, "Data")
    
    writer.save()
    

    You need to initialize writer.sheets in order to let ExcelWriter know about the sheets. Otherwise, it will create a new sheet with the name that you pass.

    0 讨论(0)
提交回复
热议问题