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

Need help to make the context dynamic #453

Closed indrastorms closed 1 year ago

indrastorms commented 1 year ago

Describe your problem

I want to make the context dynamic so I don't have to make change in code for the different templates.

Here's the code same as your demo code with bit changes

import pandas as pd
import os
from docxtpl import DocxTemplate

#Enter the complete filepath to the Word Template
#template_path = input("Insert the template file path : ")
template_path = os.getcwd() + "/sampledoc.docx"
print("Reading template from: " + template_path)

#For print variables
tpl = DocxTemplate(template_path)
variables = tpl.get_undeclared_template_variables()
print(f"\n Reading variables\n{variables}")

#Enter the complete filepath to the excel file which has the data
#source_path = input("Insert the source data file path : ")
source_path = os.getcwd() + "/source_data.xlsx"
print("\nReading source data from: " + source_path)
df = pd.read_excel(source_path)
print(f"\nPrinting source data\n{df}")

#Enter the complete filepath to the excel file where exported files will be saved
#save_dir = input("InserInsert the export directory path : ")
#os.chdir("export")
save_dir = "/storage/emulated/0/python/export/"

for variable in variables:
  locals()[variable] = df[variable].values

zipped = zip(Name,Age,Roll,Class,Score)
print("\nPerforming Mail Merge !")

for a,b,c,d,e in zipped:
  context = {"Name":a,"Age":b,"Roll":c,"Class":d,"Score":e}
  tpl.render(context)
  tpl.save(save_dir + '{}.docx'.format(a))

print("\nCongratulation! All files are exported to:\n"
       + str(save_dir[:-1]))

Want to change these bellow line dynamic so I don't have write the field name for different templates. zipped = zip(Name,Age,Roll,Class,Score)

context = {"Name":a,"Age":b,"Roll":c,"Class":d,"Score":e}

indrastorms commented 1 year ago

Solved it, for reference https://stackoverflow.com/q/73195608/19667136