在PythondOxTemplate中使用XLSX作为数据库时出现问题

2024-10-06 12:40:29 发布

您现在位置:Python中文网/ 问答频道 /正文

当我在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')}.

我做错了什么


Tags: 文件pathnameimport模板docxlsxgender
1条回答
网友
1楼 · 发布于 2024-10-06 12:40:29

这是因为pd.read\u excel会返回以下信息:

   name   birth   gender
0  felipe date    male

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

因此,当您调用df.to_dict()时,您有以下返回

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

您可以在文档https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_dict.html中看到这一点

如果您将来遇到任何问题,我建议您检查文档并打印变量,以了解问题所在

相关问题 更多 >