当我在pythondocx模板中使用XLSX文件作为数据库时,输出文件中出现了bug
XLSX文件包含:
name birth gender
Felipe 07/04/1988 male
docx中的我的模板包含:
我的名字是{{name},我是{{gender},我出生在{{birth}
这是我的代码:
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")
但是,创建“生成的文档”时,它包含以下文本:
My name is {0: 'Felipe'}, i am {0: 'male'} and i was born in {0: Timestamp('1988-04-07 00:00:00')}.
我做错了什么
这是因为pd.read\u excel会返回以下信息:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html
因此,当您调用df.to_dict()时,您有以下返回
您可以在文档https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html中看到这一点
如果您将来遇到任何问题,我建议您检查文档并打印变量,以了解问题所在
相关问题 更多 >
编程相关推荐