0

I am having problem in appending data to existing sheet of the excel file. Following is the code, which picks up the last date of record from the excel file creates new df with incremental records and I am trying to append the new records to same sheet of excel file.

import pandas as pd
import datetime as dt
import yfinance as yf
from openpyxl import load_workbook

ticker = 'AXISBANK.NS'

ef = pd.read_excel('D:/YProject/'+ticker+'.xlsx', sheet_name = 'Daily') 


en = dt.datetime.today()+ dt.timedelta(days=1)
st = ef.Date.max()+ dt.timedelta(days=1)
df = yf.download(ticker, start =st, end =en, interval ='1d').drop(['Adj Close'], axis = 1).reset_index()

writer = pd.ExcelWriter('D:/YProject/'+ticker+'.xlsx',engine='openpyxl', mode='a')
writer.book = load_workbook('D:/YProject/'+ticker+'.xlsx')
df.to_excel(writer, sheet_name = 'Daily',header='false')
writer.save()
writer.close()
print(df)

This code creates new sheet and doesnot append the sheet

Animesh Shah
  • 136
  • 9
  • 1
    I would suggest reading openpyxl documentation. I don't thinkg it allows appending to existing sheet. You may need to use xlwings – Rahul Jan 02 '21 at 05:19
  • I think I should append data to ef and save it as file – Animesh Shah Jan 02 '21 at 05:23
  • Try using the append method instead of just re-saving it? http://zetcode.com/python/openpyxl/ – Hooded 0ne Jan 02 '21 at 05:57
  • This should do it. A helper function https://stackoverflow.com/a/38075046/6713740 – rko Jan 02 '21 at 05:59
  • Additionally, your post can easily be flagged as a duplicate. – rko Jan 02 '21 at 06:05
  • 1
    Does this answer your question? [Append existing excel sheet with new dataframe using python pandas](https://stackoverflow.com/questions/38074678/append-existing-excel-sheet-with-new-dataframe-using-python-pandas) – rko Jan 02 '21 at 06:06

0 Answers0