How to paste a dataframe on a preformatted worksheet in Python?

0

I have a preformatted template in Excel that way.

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

    
asked by anonymous 16.08.2018 / 19:41

1 answer

2
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:

link

link

    
16.08.2018 / 21:00