Appending dataframe to the very same worksheet

Viewed 37

I have been searching between different questions and answers regarding open openpyxl and xlsxwriter.

I have a simple question and I am sure there is a simple answer for it.

I have a dataframe which I am trying to append to an existing xlsx file. My issue is that it keeps creating a new worksheet everytime I run the code.

I have tried several solutions but none of them work. here is the code:

        output_dict = {'Name': pd.Series(new_name),
                       'Link': pd.Series(new_url)
                       }
        df = pd.DataFrame(output_dict)
        with ExcelWriter('Links.xlsx', engine="openpyxl", mode='a') as writer:
            df.to_excel(writer, sheet_name='in')

My question is how to append df to the very same worksheet called 'in'?

1 Answers

Try replacing your with ExcelWriter block with:

with pd.ExcelWriter('Links.xlsx',mode='a') as writer:  
    df.to_excel(writer, sheet_name='in')

Note the pd.ExcelWriter, not just ExcelWriter.

This is from the pandas documentation here. Second to last code block on the page.

Related