Search code examples
excelpandasexport-to-excel

How to append the dataframe in to the excel sheet


I have a excel sheet having 5 sheets (sheet1,sheet2,sheet3,sheet4,final_df)

my dataframe df is the output, I need to save as final_df as sheet name. The final_df is already exist in the excel file with 4 line of data.so 'final_df` has append from the 5th row

How to achieve this?

While using excelwriter all the data from the sheet is vanishing


Solution

  • This should work:

    from openpyxl import load_workbook
    import pandas as pd
    book = load_workbook('final_df.xlsx')
    writer = pandas.ExcelWriter('final_df.xlsx', engine='openpyxl')
    writer.book = book
    
    # get the last row in the existing Excel sheet
    startrow = writer.sheets['Sheet1'].max_row
    
    df.to_excel(writer,['Sheet1'], startrow, index = False, header= False)
    writer.save()