Getting AttributeError 'Workbook' object has no attribute 'add_worksheet' - while writing data frame to excel sheet

前端 未结 3 464
北海茫月
北海茫月 2021-01-14 01:13

I have the following code, and I am trying to write a data frame into an "existing" worksheet of an Excel file (referred here as test.xlsx). Sheet3 is the targeted

3条回答
  •  伪装坚强ぢ
    2021-01-14 01:46

    You can use openpyxl as the engine when you are creating an instance of pd.ExcelWriter.

    import pandas as pd
    import openpyxl
    
    df1 = pd.DataFrame({'A':[1, 2, -3],'B':[1,2,6]})
    book = openpyxl.load_workbook('examples/ex1.xlsx') #Already existing workbook
    writer = pd.ExcelWriter('examples/ex1.xlsx', engine='openpyxl') #Using openpyxl
    
    #Migrating the already existing worksheets to writer
    writer.book = book
    writer.sheets = {x.title: x for x in book.worksheets}
    
    df1.to_excel(writer, sheet_name='sheet4')
    writer.save()
    

    Hope this works for you.

提交回复
热议问题