Home > Net >  How to write dataframe into existing Excel file?
How to write dataframe into existing Excel file?

Time:09-16

I want to ask you how to add dataframe as new list in existing excel file. For example, I have flat.xlsx file with 2 lists: sheet1 and sheet2. I want to add new list named Data into this file.

Can you please help me?

CodePudding user response:

If you call df.to_excel(filename) with target filename then it will overwrite an existing file. You must use a ExcelWriter.

Try this:

import pandas as pd

with pd.ExcelWriter('test.xlsx', engine='openpyxl', mode='a') as writer:    
    df = pd.read_csv('test.csv')  # open/create dataFrame to add
    df.to_excel(writer, sheet_name='new_sheet3')

CodePudding user response:

You can try with that

import pandas as pd
import numpy as np
  
x = np.random.randn(100, 2)
df = pd.DataFrame(x) #creating a random dataframe or using yours
writer = pd.ExcelWriter('flat.xlsx', engine = 'openpyxl', mode= 'a')
df.to_excel(writer, sheet_name = 'y')
writer.save()
writer.close()
  • Related