在python-docx-template中使用XLSX作为数据库的问题。

问题描述 投票:-1回答:1

当我在python-docx-template中使用XLSX文件作为数据库时,输出的文件出现了错误。

XLSX文件包含

  name    birth      gender
 Felipe   07/04/1988   male 

我的docx模板包含:

我的名字是{{姓名}}, 我是{{性别}},我出生在{{出生}}.

这是我的代码。

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")

但是,当 "generated_docx "被创建时,它包含了文本。

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

我做错了什么?

python pandas python-docx
1个回答
0
投票

这是因为pd.read_excel返回你这个。

   name   birth   gender
0  felipe date    male

https:/pandas.pydata.orgpandas-docsstablereferenceapipandas.read_excel.html)。

所以当你调用df.to_dict()时,你会得到这样的返回值

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

你可以在文档中看到 https:/pandas.pydata.orgpandas-docsstablereferenceapipandas.DataFrame.to_dict.html。

如果你以后有什么问题,我建议你查看文档,打印你的变量,看看是什么问题。

© www.soinside.com 2019 - 2024. All rights reserved.