0

I want to create bulk Word documents from Excel. There is a pre-defined Word template. I need to put names, acc numbers, etc. from Excel in the word documents. Any idea how? I tried a way by looking at a Youtuber and use Docxtpl but end up in errors.

Code looks like this:

base_dir = Path('C:\\Users\\137224\\Desktop\\HNJ\\BL\\test')
word_template_path  = base_dir / "3. Most Important Document (MID)-BL 0922.docx"
excel_path = base_dir / "Untitled 1.xlsx"
output_dir = base_dir / "OUTPUT"
output_dir.mkdir(exist_ok=True)
df = pd.read_excel(excel_path, sheet_name="Sheet1")
for record in df.to_dict( orient= "records" ):
    #record = str(record)
    doc = DocxTemplate(word_template_path)
    doc.render(str(record))
    output_path = output_dir / f"{record['Loan Account Number']}-contract.docx"
    doc.save(output_path)

Error looks like this:

ValueError                                Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_14792/316463526.py in <module>
      2     #record = str(record)
      3     doc = DocxTemplate(word_template_path)
----> 4     doc.render(str(record))
      5     output_path = output_dir / f"{record['Loan Account Number']}-contract.docx"
      6     doc.save(output_path)

C:\ProgramData\Anaconda3\lib\site-packages\docxtpl\template.py in render(self, context, jinja_env, autoescape)
    341 
    342         # Body
--> 343         xml_src = self.build_xml(context, jinja_env)
    344 
    345         # fix tables if needed

C:\ProgramData\Anaconda3\lib\site-packages\docxtpl\template.py in build_xml(self, context, jinja_env)
    288         xml = self.get_xml()
    289         xml = self.patch_xml(xml)
--> 290         xml = self.render_xml_part(xml, self.docx._part, context, jinja_env)
    291         return xml
    292 

C:\ProgramData\Anaconda3\lib\site-packages\docxtpl\template.py in render_xml_part(self, src_xml, part, context, jinja_env)
    237             else:
    238                 template = Template(src_xml)
--> 239             dst_xml = template.render(context)
    240         except TemplateError as exc:
    241             if hasattr(exc, 'lineno') and exc.lineno is not None:

C:\ProgramData\Anaconda3\lib\site-packages\jinja2\environment.py in render(self, *args, **kwargs)
   1084         This will return the rendered template as unicode string.
   1085         """
-> 1086         vars = dict(*args, **kwargs)
   1087         try:
   1088             return concat(self.root_render_func(self.new_context(vars)))

ValueError: dictionary update sequence element #0 has length 1; 2 is required
shafee
  • 15,566
  • 3
  • 19
  • 47
  • "How can I take data hidden in one fugly opaque legacy document format and hide it in another fugly opaque legacy document format" seems slightly hard to reconcile with anything "better". – tripleee Oct 29 '22 at 08:21

0 Answers0