最近需要从Oracle数据库中提取一些数据,并使用文档模板生成文档,鉴于Python环境部署的方便性,编程的简便性,于是采用Python开发该程序。方法记录如下:
环境配置 依赖环境 核心是 docxtpl 和 oracledb 两个库。
python 3.8.5,可在windows7上运行,python 3.9以后版本不支持windows7
Babel==2.15.0
cffi==1.16.0
cryptography==42.0.8
docxcompose==1.4.0
docxtpl==0.17.0
jinja2==3.1.4
lxml==5.2.2
MarkupSafe==2.1.5
numpy==1.24.4
oracledb==2.2.1
pandas==2.0.3
pycparser==2.22
python-dateutil==2.9.0.post0
python-docx==1.1.2
pytz==2024.1
six==1.16.0
typing-extensions==4.12.2
tzdata==2024.1
虚拟环境 1 2 3 4 5 6 7 mkdir wordtpl_generate cd wordtpl_generate python -m venv env env\Scripts\activate.bat pip install pandas pip freeze > requirement.txt pip download -d packages -r requirement.txt
离线迁移 创建envConfig.bat批处理文件,一键执行离线环境配置。
1 2 3 python -m venv env call env\Scripts\activate.bat pip install --no-index --find-links=packages -r requirements.txt
具体实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import getpass import oracledb from docxtpl import DocxTemplate def oracledb_test(): un = 'scott' cs = 'localhost/orclpdb' pw = getpass.getpass(f'Enter password for {un}@{cs}: ') with oracledb.connect(user=un, password=pw, dsn=cs) as connection: with connection.cursor() as cursor: sql = """select sysdate from dual""" for r in cursor.execute(sql): print(r) def wordtpl_test(): doc = DocxTemplate("my_word_template.docx") context = { 'company_name' : "World company" } doc.render(context) doc.save("generated_doc.docx") if __name__ == '__main__': oracledb_test() wordtpl_test()
参考链接
Python自动化:根据模板批量生成含指定数据的word文档 ,by aliyun.