Python將數據渲染到docx文檔指定
- 2020 年 1 月 17 日
- 筆記
超簡單Python將指定數據插入到docx模板渲染並生成
最近有一個需求,製作勞動合約表,要從excel表格中將每個人的數據導入到docx勞動合約中,重複量很大,因此可以使用python高效解決。為了讓模板內容不變動,這裡使用了類似jinja2的渲染引擎,使用{{ }}插值表達式把數據插入進去。也可以使用{% %}循環,條件語法等。
docx模板如下(在需要插值的位置填充 {{}} 表達式):

首先安裝docxtpl
$ pip install docxtpl
python程式碼如下:
from docxtpl import DocxTemplate tpl = DocxTemplate('勞動合約.docx') #這些欄位從csv中獲取 context = { "name": name, "department": department, "position": position, "time": time, "id": id_card, "addr": addr, } tpl.render(context) tpl.save("{}的勞動合約.docx".format(name))