简体   繁体   中英

Python Excel write a DataFrame in an existing sheet

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()

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM