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

Unable to open generated word file (Word experienced an error trying to open the file) #489

Closed stefanomattia closed 1 year ago

stefanomattia commented 1 year ago

Describe the bug

Unable to open generated word file

To Reproduce

I am using the following code:

from docxtpl import DocxTemplate

context = {'requirements' : [{'id': '0010',
  'description': 'first requirement',
  'category': 'functional',
  'applicability': 'all',
  'justification': 'self explanatory'},
 {'id': '0020',
  'description': 'second requirement',
  'category': 'functional',
  'applicability': 'X',
  'justification': 'self explanatory'}]}

doc = DocxTemplate("gsrd_template.docx")
doc.render(context)
doc.save("generated_doc.docx")

The gsrd_template.docx is a simple word document with the following content:

Screenshot 2023-04-19 at 17 53 50

Expected behavior

I would expect the generated word document to contain two tables for each of the two defined requirements in the context dictionary. However, even if there are no errors during the code execution, the generated word document can't be opened (see screenshot). Screenshot 2023-04-19 at 17 56 34

Additional context

I am using Python 3.9.31, docxtpl 0.11.5 (installed via conda), python-docx 0.8.11, Word for Mac 16.72

elapouya commented 1 year ago

The {% for / endfor must be inside the table : have a look to tests/ directory in source code to have exemples.

stefanomattia commented 1 year ago

Thank you for the quick response.

Putting the for and enfor inside the table (on a merged row) kind of works (some spurious cells at the end), but I get one table with the two requirements concatenated (see screenshot). However, I would like to have two separate tables, hence I put the for and endfor outside the table template, is that possible?

Screenshot 2023-04-19 at 18 09 08

The template I used is:

Screenshot 2023-04-19 at 18 10 23
elapouya commented 1 year ago

Sorry, I haven't seen that point, so what you did was almost good : put for loop outside the table but use {%p instead of {%tr

stefanomattia commented 1 year ago

Awesome, this works, thanks a lot!