0

I use some condition to df and all of variants I try write to one excel file(and to one Sheet). I use code from question, my df is

for i, (id, date, url, id1, date1) in enumerate(zip(ids, dates, urls, ids1, dates1)):
    df_upd = df[(df['ID'] == ids1[i]) & (df['used_at'] < (dates1[i] + dateutil.relativedelta.relativedelta(days=5)).replace(hour=0, minute=0, second=0)) & (df['used_at'] > (dates1[i] - dateutil.relativedelta.relativedelta(months=1)).replace(day=1, hour=0, minute=0, second=0))]

and after I use code

book = load_workbook('report_buy.xlsx')
writer = pd.ExcelWriter('report_buy.xlsx', engine='openpyxl')
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
df_upd.to_excel(writer)

but it overwriting my file. What's wrong there?

Community
  • 1
  • 1
Arseniy Krupenin
  • 3,800
  • 3
  • 13
  • 18

1 Answers1

0

I dont think you can update cell contents. You can open a file to read, or open a new file to write to. I think you have to create a new workbook, and every cell that you read, if you choose to not modify it, write it out to your new workbook. In your sample code, you are overwriting wb (used to read) with the wb (used to write). Pull it out of the for loop, assign a different name to it.

import openpyxl
xfile = openpyxl.load_workbook('test.xlsx')
sheet = xfile.get_sheet_by_name('Sheet1')
sheet['A1'] = 'hello world'
xfile.save('text2.xlsx')

I found these in following links here and here

Community
  • 1
  • 1
sathish
  • 149
  • 9