elapouya / python-docx-template

Use a docx as a jinja2 template
GNU Lesser General Public License v2.1
1.91k stars 378 forks source link

Dynamic table in docx from excel #475

Closed ghost closed 1 year ago

ghost commented 1 year ago

Hello, I need some help, please. I'm trying to get many word documents from a excel data frame by a variable group (Date + Topic)

image

The final result that I would like to obtain is a document like this for each value of the group variable (Topic):

image

`from pathlib import Path

import pandas as pd from docxtpl import DocxTemplate from docx import Document from datetime import datetime import jinja2 import itertools

base_dir =Path(file).parent word_template_path = base_dir / "Word-Template.docx" excel_path = base_dir / "Base_2020.xlsx"

output_dir = base_dir / "OUTPUT"

output_dir.mkdir(exist_ok=True)

Excel a df

df = pd.read_excel(excel_path,sheet_name="Sheet1")

#######################

df['Date'] = df.Date.dt.strftime("%d-%m-%Y") df['Fecha_compromiso'] = df.Fechacompromiso.dt.strftime("%d-%m-%Y") df['group'] = df['Date'] + "" + df['Topic'] df['Fecha_compromiso'] = df['Fecha_compromiso'].fillna('')

for value in df['group'].unique(): for record in df.loc[df.group == value].to_dict("records"): doc = DocxTemplate(word_template_path) jinja_env = jinja2.Environment(autoescape=True) doc.render(record, jinja_env) output_path = f"{output_dir}/{record['group']}.docx" doc.save(output_path)

`and my template:

image

I obtain this:

image

juanboterotech commented 1 year ago

record var is a dictionary?

elapouya commented 1 year ago

You are rendring one record, you have to render one context which must be a dict containing a list of records at key 'Topic'.