-1

When I use a XLSX file as database in my python-docx-template, the output file came with bugs.

The XLSX file contains:

  name    birth      gender
 Felipe   07/04/1988   male 

My template in docx contains:

My name is {{ name }}, i am {{ gender }} and i was born in {{ birth }}.

This is my code:

import pandas as pd
from docxtpl import DocxTemplate

file_path = 'test.xlsx'
df = pd.read_excel(file_path, encoding='utf-8')
data = df.to_dict()

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

but, when the "generated_docx" is created, it contains the text:

My name is {0: 'Felipe'}, i am {0: 'male'} and i  was born in {0: Timestamp('1988-04-07 00:00:00')}.

What am I doing wrong??

1 Answers1

0

It is because pd.read_excel return you this :

   name   birth   gender
0  felipe date    male

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html

So when you call df.to_dict() you have this return

{'name': {'0': 'felipe'}, 'birth': {'0':  Timestamp('1988-04-07 00:00:00'), 'gender':{'0': 'male'}}

You can see this in the documentation https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html

If you have any trouble in the future, I suggest you to check documentation and print your variables to see what is the problem.

thomaslecouffe
  • 144
  • 1
  • 6
  • Thanks thomaslecouffe. I changed my function 'to_dict ()' to 'to_dict (orient = 'list')' and it almost worked, as the result is‘{'name': ['Felipe'], ...}',and the brackets are appearing in the final document, with the text generated by DocxTemplate being printed like this: 'My name is ['felipe'], i am ['male']...' If I use the function ‘data ['name'] = 'felipe' 'it works, because it changes the dictionary from '{'name': ['felipe'] ..}' to '{'name': 'felipe' ..}'. Therefore, I need to find out how to remove the brackets from the created dictionary, but I'm not getting. Im new in Python. – Felipe Lemes Jun 08 '20 at 16:59
  • I fixed using this dict comprehension: `data = {key: value[0] if isinstance(value, list) else value for key, value in data.items()} ' – Felipe Lemes Jun 08 '20 at 18:21