Python + docxtpl + MongoDB快速生成word

编程入门 行业动态 更新时间:2024-10-24 04:45:42

Python + docxtpl + MongoDB<a href=https://www.elefans.com/category/jswz/34/1771431.html style=快速生成word"/>

Python + docxtpl + MongoDB快速生成word

Python + docxtpl + MongoDB快速生成word

安装所需要的环境

安装Python环境
安装MongoDB数据库
安装所需要的第三方包(pymongo,docxtpl)

实现过程及原理

查询mongdb数据库,准备好要生成word文档的数据,在word模板中进行渲染,保存生成的word

详细步骤

获取命令行参数

由于我的功能函数所需要的参数是由命令行传过来的,我需要接收命令行参数,接收代码如下,返回的参数为命令行参数的获取字典.这里我接收参数的格式为python python.py -p ‘proj_id’ -t ‘模板路径’ -v ‘version’ -r ‘run_id’

import getopt
import sysdef get_args():"""获取命令行参数"""arg_path = {}try:opts, args = getopt.getopt(sys.argv[1:], "p:r:v:t:", ["--proj_id", "--run_id", "version", "template"])del argsexcept getopt.GetoptError:raise ValueError('输入参数错误')for name, value in opts:if name in ("-p", "--proj_id"):arg_path["proj_id"] = valueif name in ("-r", "--run_id"):arg_path["run_id"] = valueif name in ("-v", "--version"):arg_path["version"] = valueif name in ("-t", "template"):arg_path["template"] = valuereturn arg_path
利用pymongo连接MongoDB数据库

代码如下

import pymongodef comm_db():"""链接数据库"""client = pymongo.MongoClient(host='127.0.0.1', port=27017)db = client.mydb #数据库名称mydbreturn db
  • 这里我把以上两个功能函数封装在一起当作模块导入
数据库数据的查询
  • 根据查询条件查出所需要的数据,集合为my_collections
  • 查询条件为proj_id与version,二者联合唯一
  • 代码如下
def get_proj_docx(proj_id, version):if version is None:version = ''file_json = comm_db()['my_collections'].find_one({"proj_id": proj_id"version": version})if file_json is None:raise Exception('数据库查询错误')return file_json
数据的处理

由于一些数据的计算标题的处理需要在代码中完成,这里我做了一些处理

  • 为树形结构递归创建标题
  • 计算树形结构的数据的个数
  • json序列化我需要展示的数据格式等
  • 获取当前节点的父节点
def get_tpoic(children, s):for index, value in enumerate(children):del valuechildren[index]['top'] = s + '.' + str(index + 1)child = children[index].get('children', None)if children[index] and child is not None:get_tpoic(children[index]['children'], children[index]['top'])def get_result(run_tree, total):for da in run_tree:if run_info is not None:test_data = run_info.get('test_data', None)if test_data is not None:run_info['test_data'] = json.dumps(test_data, indent=8)def findparentdict(parent, node_id):par_get = parent.get('children', None)if parent is None or par_get is None:return Nonefor it in par_get:if it['id'] == node_id:return parentfor item in par_get:if it['kind'] == 'dir':res = findparentdict(item, node_id)if res:return resreturn None

这里只展示典型的数据处理

word模板的准备

这就就要用到jinja2的语法,类似于MVC开发模式的前端语法简单举例

{% if True %}{{‘我是小明’}}{% else %}{{ ‘我不是小明’ }}{% endif %}
模板的准备需要根据用户的需求进行自定义模板的类型,模板的语法这里让我头疼了好久,书写错误无法排错,只能慢慢查找(我没有找到好的拍错的方法)

  • 这里介绍一下模板中使用的递归函数(宏递归)
    {% macro factorial(run_tree) -%}
    {。。。。。}
    {{- factorial(run.children) -}}
    {。。。。。}
    {%- endmacro %}
    {{ factorial(run_tree[0].children) }}
  • 以下为word模板语法中的部分代码
  • 根据需求自行定义
  • jinja2的语法下一期作介绍
进行模板的渲染

处理好的数据与事先准备好的模板作为参数传进来

def get_word(file, templete):if isinstance(file, dict):docx = DocxTemplate(template)docx.render(file)name = file['name'] + ".docx"docx.save(name) #保存在当前路径下else:raise Exception("数据格式错误")

插入图片

简单示例

	from docxtpl import DocxTemplate, InlineImagefrom docx.shared import Mmdef getimg():docx = DocxTemplate("demo.docx")insert_image2 = InlineImage(docx, "qwe.png", width=Mm(140))docx.render({"img": insert_image2})docx.save("demo_1.docx")

更多推荐

Python + docxtpl + MongoDB快速生成word

本文发布于:2024-02-14 10:41:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1763318.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快速   docxtpl   Python   word   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!