0

I'd like to add a dataframe in an existing sheet (here "sheet1") but the code creates a new "sheet1". Here is my code:

Thank you very much for your help

Alex

import pandas as pd
import numpy as np
from openpyxl import load_workbook

path = ""
df = pd.DataFrame({'Data': [11, 12, 13, 14]})
book = load_workbook(path)
writer = pd.ExcelWriter(path, engine = 'openpyxl')
writer.book = book
df.to_excel(writer,sheet_name="Sheet1" startrow=1, startcol=5, header=False,index=False)
writer.save()
writer.close()
Alex
  • 1
  • Not with openpyxl. My file is not erased but just, it creates a new sheet. I want to write in sheet[0]. – Alex Dec 17 '19 at 17:08
  • 1
    https://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data-using-pandas – BigBen Dec 17 '19 at 17:11
  • ^ from that thread this is the post you need https://stackoverflow.com/a/47740262/9375102 – Umar.H Dec 17 '19 at 17:18
  • Thanks a lot. Just I don't want "max_row" as mentionned but row= 6 for example. How can I do? Thank you – Alex Dec 17 '19 at 17:31

2 Answers2

0

I was wondering if you just bring in the whole xl library? I haven't tried pandas yet, but it's on my project roadmap.

    import openpyxl
0

You can try this:

from openpyxl import load_workbook

wb = load_workbook("C:\text.xlsx")
sheets = wb.sheetnames
Sheet1 = wb[sheets[8]]
Sheet2 = wb[sheets[7]]
#Then update as you want it
Sheet1 .cell(row = 2, column = 4).value = 5 #This will change the cell(2,4) to 4
wb.save("HERE PUT THE NEW EXCEL PATH") 

for more information : enter link description here