Skip to content

Instantly share code, notes, and snippets.

@villares
Created November 9, 2023 01:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save villares/560e231da78cd1b8f5701c5a6897348f to your computer and use it in GitHub Desktop.
Save villares/560e231da78cd1b8f5701c5a6897348f to your computer and use it in GitHub Desktop.
Lê uma planilha de Excel e altera um arquivo de Word
from docx import Document
import openpyxl
d = Document('template.docx') # template
wb = openpyxl.load_workbook('dados.xlsx') # planilha de dados
fs = wb.worksheets[0] # first sheet (primeira folha)
def substitui(d, busca, subst):
for p in d.paragraphs:
for r in p.runs:
if busca in r.text:
r.text = r.text.replace(busca, subst)
filas = list(fs.rows)[1:] # filas a partir da segunda
dados = {} # dicionário vazio
for fila in filas:
a, b = fila[:2] # duas primeiras células da fila
if a.value: # if a.value is not None:
dados[a.value] = b.value
for chave, valor in dados.items():
substitui(d, chave, valor)
output = f"{dados['[CERTIFICADO]']}-{dados['[NOME]']}.docx"
d.save(output)
print(f'Salvo em {output}...')
exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment