2

You can find what I've tried so far below:

import pandas
from openpyxl import load_workbook

book = load_workbook('C:/Users/Abhijeet/Downloads/New Project/Masterfil.xlsx')
writer = pandas.ExcelWriter('C:/Users/Abhijeet/Downloads/New Project/Masterfiles.xlsx', engine='openpyxl',mode='a',if_sheet_exists='replace') 
df.to_excel(writer,'b2b')

writer.save()
writer.close()
Muhteva
  • 2,729
  • 2
  • 9
  • 21

2 Answers2

0

Generate Sample data

import pandas as pd

# dataframe Name and Age columns
df = pd.DataFrame({'Col1': ['A', 'B', 'C', 'D'],
                   'Col2': [10, 0, 30, 50]})

# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('sample.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1', index=False)

# Close the Pandas Excel writer and output the Excel file.
writer.save()

This code will add two columns, Col1 and Col2, with data to Sheet1 of sample.xlsx.

To Append data to existing excel

import pandas as pd
from openpyxl import load_workbook
# new dataframe with same columns
df = pd.DataFrame({'Col1': ['E','F','G','H'],
                   'Col2': [100,70,40,60]})
writer = pd.ExcelWriter('sample.xlsx', engine='openpyxl')
# try to open an existing workbook
writer.book = load_workbook('sample.xlsx')
# copy existing sheets
writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets)
# read existing file
reader = pd.read_excel(r'sample.xlsx')
# write out the new sheet
df.to_excel(writer,index=False,header=False,startrow=len(reader)+1)

writer.close()

This code will append data at the end of an excel.

Check these as well

how to append data using openpyxl python to excel file from a specified row?

Ailurophile
  • 2,552
  • 7
  • 21
  • 46
-1

Suppose you have excel file abc.xlsx. and You Have Dataframe to be appended as "df1"

1.Read File using Pandas

import pandas as pd
df = pd.read_csv("abc.xlsx")

2.Concat Two dataframes and write to 'abc.xlsx'

finaldf = pd.concat(df,df1)
# write finaldf to abc.xlsx and you are done