How to paste a dataframe over a pre-formatted Python worksheet?

Asked

Viewed 1,260 times

0

I have a template pre-formatted in Excel this way. template.xlsx

I would like to paste values from a dataframe into pandas on these cells, creating a new file formatted with values and keeping the original file. How do I do that?

2 answers

4


import pandas as pd
from openpyxl import load_workbook

df = pd.DataFrame(data={'Dados1': ['Ola','tudo','bom']})

#carrego o Excel com o template pré-formatado 'template.xlsx'
book = load_workbook('template.xlsx')

#defino o writer para escrever em um novo arquivo 'arquivo_editado.xlsx'
writer = pd.ExcelWriter('arquivo_editado.xlsx', engine='openpyxl')

#incluo a formatação no writer
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)

#Escrevo com o .to_excel() do pandas
df.to_excel(writer,'Sheet1')

# para escrever só os valores em um lugar específico:
df.to_excel(writer, 'Sheet1', startrow=1, startcol=1, header=False, index=False)

writer.save()

Sources:

https://xlsxwriter.readthedocs.io/working_with_pandas.html

https://stackoverflow.com/questions/20219254/how-to-write-to-an-existing-excel-file-without-overwriting-data-using-pandas

  • Perfect! I had already seen this second link you sent, but I was not able to adapt to this exact problem. Thank you!

  • Unfortunately the pandas Uga a few edges (some contours just disappear)... I think I’ll have to fix them hard-coded even, but your answer has already made 95% of what I needed.

  • Excellent, but my file has several tabs, I wanted to put the data of the dataframe in a specific tab, has as?

  • In function df.to_excel(), I believe it’s just changing the string 'Sheet1' by the name of the tab.

  • I made that attempt, it didn’t work

-2

Maybe if you add sheet= ' ' in book = load_workbook('template.xlsx') work, but I have not tested

that way:

book = load_workbook('template.xlsx', sheet = 'nome_da_aba')

in the same way as if you were going to read an Excel normally in pandas.

pd.read_excel('arquivo.xlsx', sheet = 'nome_da_aba', engine = 'openpyxl')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.