分享

使用PYTHON-DOCX & DOCXTPL生成WORD文档

 wenxuefeng360 2022-08-19 发布于四川

最近需要用python生成Word文档,期间用到了python-docx 和 docxtpl库,这两者都可以用pip安装。

1、安装方法:

  1. $ pip install python-docx
  2. $ pip install docxtpl

python-docx 相对比较难安装一点,可能会遇到坑,可以参考这篇博客上的方法:在Windows上安装python-doc

docxtpl 比较好安装,基本都是一次成功。

2、使用方法:

  1. # coding:utf-8
  2. from docxtpl import DocxTemplate, InlineImage
  3. from docx.shared import Pt
  4. def generate_report(tpl_file, report_file):
  5. tpl = DocxTemplate(tpl_file)
  6. context = {
  7. "year": "2020",
  8. "month": "08",
  9. "day": "30",
  10. "hour": "11",
  11. "minute": "00",
  12. "figure1": InlineImage(tpl, "timg.jpeg", width=Pt(205), height=Pt(185)),
  13. "name": "zhoumin"
  14. }
  15. tpl.render(context)
  16. tpl.save(report_file)
  17. def main():
  18. tpl_file = "template.docx"
  19. report_file = "report.docx"
  20. generate_report(tpl_file, report_file)
  21. if __name__ == "__main__":
  22. main()

模板文档:

生成文档:

3、备注

  • 图片居中的方法:在模板中将待替换的内容设为居中样式
  • 模板文件名称 和 生成文件名称最好不要用中文,在Windows上可以会报错。 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多